【发布时间】:2012-06-16 16:05:31
【问题描述】:
我必须在一个 4bytes 的文件中写入一个小端(java 使用大端)表示整数的文件,因为外部 c++ 应用程序必须读取这个文件。我的代码没有在 te 文件中写入任何内容,但 de 缓冲区中有数据。为什么? 我的功能:
public static void copy(String fileOutName, boolean append){
File fileOut = new File (fileOutName);
try {
FileChannel wChannel = new FileOutputStream(fileOut, append).getChannel();
int i = 5;
ByteBuffer bb = ByteBuffer.allocate(4);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.putInt(i);
bb.flip();
int written = wChannel.write(bb);
System.out.println(written);
wChannel.close();
} catch (IOException e) {
}
}
我的电话:
copy("prueba.bin", false);
【问题讨论】:
-
不要忽略异常。在
catch块中写入e.printStackTrace() -
我试过那个代码,它在文件中写入了 4 个字节
-
这可能是非同步 IO 的问题。 write 方法不会阻塞,因此无法保证它会在您调用 close 时完成。并且 close 强制阻塞的线程立即退出,这可能会中止写入并出现您忽略的异常。
标签: java io nio bytebuffer endianness