我希望这个程序在我的txt文件中写入数字,但是它不会写一些奇怪的signs.Does,任何人都可以修复它,并使它从数组中写入数字。
package int1;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;
public class broj_u_skl {
public static void main(String[] args) {
File a = new File("C:\\Users\\Jovan\\Desktop");
File b = new File(a,"Pisem.txt");
try {
b.createNewFile();
}catch(Exception e) {
}
FileOutputStream st = null;
try {
st = new FileOutputStream(b);
}catch(Exception e) {
}这是一个数组:
int[] c = {1,2,3,4,5,6,7,8,9};但是上面没有写这个数字。
ByteBuffer bff = ByteBuffer.allocate(100);
FileChannel ch = st.getChannel();
IntBuffer ib = bff.asIntBuffer();
for (int i = 0; i < c.length; i++) {
ib.put(c[i]);
}
bff.position(4*ib.position());
bff.flip();
try {
ch.write(bff);
}catch(IOException e) {
}
}
}发布于 2017-08-11 10:34:10
您可以在finally子句中结束st。
FileOutputStream st = null;
try {
st = new FileOutputStream(b);
...
} catch(Exception e) {
...
} finally {
st.close();
}或者一个更好的解决方案是使用一个尝试资源子句,它将为您关闭st。
try (FileOutputStream st = new FileOutputStream(b)) {
...
} catch(Exception e) {
...
}发布于 2017-08-11 10:28:21
添加以下代码
finally{
st.close();
}发布于 2017-08-11 10:39:12
这样做的目的是将整数作为字节写入文件,而不是作为ascii字符串。
https://stackoverflow.com/questions/45632878
复制相似问题