Reading binary to string

This should be obvious, but I can't figure it out. I spent almost the whole day on this. I would love to buy a beer for someone who can make it easier for 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 size of the byte array is not suitable, but I can not determine the desired size. In addition, the content is also not incorrect. Only text characters seem to be in order.

It looks like the data from the binary is a real pain, I am really depressed.

One more thing: the content of the file is not text, it can be like a picture, video or PDF.

+4
source share
2 answers

If you are reading a binary, you should not try to process it as if it were encoded text. Converting it to a string like this is wrong - you should store it as an array of bytes. If you really need it as text, you should use base64 or hex to represent binary data - other approaches may lose data.

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

+10
source

As Jon Skeet told you (and you should always listen to someone with 347k!), If this is not text, do not save it in a string and save it as a byte array. Also, try commons-io and use its helper classes.

 File file = new File(filePath); InputStream is = null; byte[] bytes = null; try{ bytes = IOUtils.toByteArray(is); }finally{ IOUtils.closeQuietly(is) } 
0
source

All Articles