Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a binary file into a string

It must be obvious, but I can't figure it out. I spent almost a whole day for this. I'll gladly buy a beer to someone who can lighten me.

File file = new File(filePath);
byte[] bytes = new byte[(int)file.length()];
DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
dataInputStream.readFully(bytes);           
dataInputStream.close();            
return new String(bytes);

This is my code. I see that the byte array size is not OK, but I can't figure out the right size. Besides that the contents are not also incorrect. It seems that only the text characters are OK.

It seems get out the data from a binary file is a real pain, I'm really depressed.

One more thing: the file contents are not text, it can be anything like a picture, video, or pdf.

like image 273
Sandor Avatar asked Sep 19 '11 19:09

Sandor


1 Answers

If you're reading a binary file you should not try to treat it as if it were encoded text. It's inappropriate to convert it to a string like this - you should keep it as a byte array. If you really need it as text, you should use base64 or hex to represent the binary data - other approaches are likely to lose data.

If readFully returned without an exception, that shows it's read as much data as you requested, which should be the whole file. You've managed to get the data from a binary file fairly easily (although the close() call should be in a finally block) - it's only converting it to text which is a bad idea.

like image 186
Jon Skeet Avatar answered Sep 24 '22 15:09

Jon Skeet