Hello I have the following code:
int i=12345;
DataOutputStream dos=new DataOutputStream(new FileOutputStream("Raw.txt"));
dos.write(i);
dos.close();
System.out.println(new File("Raw.txt").length());
The file size is being reported as 1 byte. Why is it not 4 bytes when an integer is 4 bytes long?
Thanks
While the
DataOutputStream.writemethod takes anintargument, it actually only writes the bottom 8 bits of that argument. So you actually wrote only one byte … and hence the file is one byte long.If you want to write the entire
intyou should use thewriteInt(int)method.The underlying reason for this strangeness is (I believe) that the
write(int)method is defined to be consistent withOutputStream.write(int)which in turn defined to be consistent withInputStream.read().InputStream.read()reads abyteand returns it as anint… with the value-1used to indicate the end-of-stream condition.