开发者

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 m开发者_StackOverflow中文版ore thing: the file contents are not text, it can be anything like a picture, video, or pdf.


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.


As Jon Skeet told you (and you should always listen someone with 347k!), if it is not a text, do not save it in a string and keep 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜