java 将二进制文件读入字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7476280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading a binary file into a string
提问by Sandor
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.
还有一件事:文件内容不是文本,它可以是图片、视频或 pdf 之类的任何内容。
回答by Jon Skeet
If you're reading a binary file you should nottry 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 reallyneed it as text, you should use base64 or hex to represent the binary data - other approaches are likely to lose data.
如果你正在读一个二进制文件,你应该不尝试把它当作好像它编码的文本。将其转换为这样的字符串是不合适的 - 您应该将其保留为字节数组。如果你真的需要它作为文本,你应该使用 base64 或 hex 来表示二进制数据 - 其他方法可能会丢失数据。
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.
如果readFully
无一例外地返回,则表明它读取的数据与您请求的一样多,这应该是整个文件。您已经设法相当容易地从二进制文件中获取数据(尽管close()
调用应该在 finally 块中) - 它只是将其转换为文本,这是一个坏主意。
回答by Pablo Grisafi
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.
正如 Jon Skeet 告诉你的(你应该总是听 347k 的人!),如果它不是文本,不要将它保存在字符串中并将其保存为字节数组。另外,试试 commons-io 并使用它的辅助类。
File file = new File(filePath);
InputStream is = null;
byte[] bytes = null;
try{
bytes = IOUtils.toByteArray(is);
}finally{
IOUtils.closeQuietly(is)
}