当我遇到这个奇怪的问题时,我正在使用 ByteBuffers 和 IntBuffers。这是代码 -
public static void main(String[] args) {
File file = null;
FileOutputStream fos = null;
FileChannel fc = null;
ByteBuffer bb = ByteBuffer.allocate(1024);
IntBuffer ib = bb.asIntBuffer();
ib.put(458215);
// System.out.println(bb.getInt()); //uncomment this for the program to work flawlessly
try {
// Initialize with object references
file = new File("E:/demjavafiles/text.txt");
fos = new FileOutputStream(file);
fc = fos.getChannel();
System.out.println("Object refrence variables file, fos, fc initialized. Now writing to file....");
System.out.println("before flip positon : " + bb.position()+ "\n limit: " + bb.limit());
bb.flip();
System.out.println("after flip positon : " + bb.position()+ "\n limit: " + bb.limit());
fc.write(bb);// write buffer
fc.close();
System.out.println("buffer written successfully!!");
} catch (Exception e) {
System.outprintln("oh oh an error occured D: heres some message 'bout it.");
e.getMessage();
e.printStackTrace(System.out);
} finally {
System.out.println("End of program....");
}
}
现在,如您所见,程序创建 aByteBuffer
和 anIntBuffer
并使用类的put()
方法IntBuffer
将 an 添加int
到ByteBuffer
4 个字节。System.out.println(bb.getInt());
当我在 try 块语句注释之前运行程序时, 这是我的输出 -
Object reference variables file, fos, fc initialized. Now writing to file....
before flip position : 0
limit: 1024
after flip posiiton : 0
limit: 0
buffer written successfully!!
End of program....
System.out.println(bb.getInt());
现在,当我使用未注释的语句再次运行它时, 这就是我的输出 -
458215
Object reference variables file, fos, fc initialized. Now writing to file....
before flip position : 4
limit: 1024
after flip position : 0
limit: 4
buffer written successfully!!
End of program....
那么谁能告诉我为什么会这样?