I was working with ByteBuffers and IntBuffers when I came across this weird problem. Here's the code -
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....");
}
}
Now the program as you can see creates a ByteBuffer
and an IntBuffer
and using the put()
method of the IntBuffer
class it adds an int
to the ByteBuffer
as 4 bytes. When I ran the program with the System.out.println(bb.getInt());
before the try block statement commented this was my output-
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....
Now when I ran it again with the System.out.println(bb.getInt());
statement uncommented this was my output-
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....
So can anyone please tell me why is this happening?