この奇妙な問題に遭遇したとき、私は 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....");
}
}
ご覧のとおり、プログラムは と を作成しByteBuffer
、クラスのメソッドをIntBuffer
使用してを 4 バイトとしてに追加します。try ブロックステートメントがコメントされる前にプログラムを実行したとき、 これが私の出力でした-put()
IntBuffer
int
ByteBuffer
System.out.println(bb.getInt());
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....
では、なぜこれが起こっているのか誰か教えてください。