I am using Java to write a byte array to a file. When I open my file in a hex editor I am not always seeing the bytes that I expected to be there. Here is my example code and contents of the output file:
public static void main(String[] args)
{
File file = new File( "c:\\temp\\file.txt" );
file.delete();
FileOutputStream outStream = null;
try
{
file.createNewFile();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
try
{
outStream = new FileOutputStream( file );
} catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
try
{
outStream.write( new byte[] { 0x14, 0x00, 0x1F, 0x50 } );
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
When I open the file in a hex editor I get 00 9e f3 04
as the contents instead of the bytes that I sent. My results seem to be inconsistent. Sometimes I get the expected result and sometimes I do not.
This will output the correct data:
outStream.write( new byte[] { 0x14 , 0x00, 0x1F, 0x50, (byte) 0xE0, 0x4F, (byte) 0xD0, 0x20, (byte) 0xEA, 0x3A, 0x69, 0x10, (byte) 0xA2 , (byte) 0xD8, 0x08, 0x00, 0x2B } );
File contents are:
14 00 1f 50 e0 4f d0 20 ea 3a 69 10 a2 d8 08 00 2b
If I add one more byte to that array then it fails.
outStream.write( new byte[] { 0x14 , 0x00, 0x1F, 0x50, (byte) 0xE0, 0x4F, (byte) 0xD0, 0x20, (byte) 0xEA, 0x3A, 0x69, 0x10, (byte) 0xA2 , (byte) 0xD8, 0x08, 0x00, 0x2B, 0x30 } );
File contents are now:
14 e5 80 9f e4 bf a0 e2 83 90 e3 ab aa e1 81 a9 ed a2 a2 08 e3 80 ab
I also had trouble with this one:
outStream.write( new byte[] { 0x4C, 0x00, 0x00, 0x00 } );
File contents are:
4c 00
The last two bytes are not written.
outStream.write( new byte[] { 0x4C, 0x00, 0x00, 0x00, 0x01 } );
This will produce the expected result. File contents are:
4c 00 00 00 01
I feel like I am missing something fundamental about the way data is written to files. How can get consistent results when writing byte arrays to a file?
.flush()
then.close()
after you.write()
... – BambooWriter
anywhere? OrString
values? Also: thecreateNewFile()
call should not be necessary. – Monophthong