将二进制文件读入字符串 [英] Reading a binary file into a string

查看:139
本文介绍了将二进制文件读入字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一定是显而易见的,但我无法弄清楚。
我花了差不多一整天的时间。
我很乐意给可以照亮我的人买啤酒。

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.

还有一件事:文件内容不是文本,可以是图片,视频或pdf。

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

推荐答案

如果您正在阅读二进制文件,则会尝试将其视为编码文本。将它转换为这样的字符串是不合适的 - 你应该把它保存为字节数组。如果确实需要它作为文本,则应使用base64或hex来表示二进制数据 - 其他方法可能会丢失数据。

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.

如果 readFully 在没有异常的情况下返回,则表明它读取的数据与您请求的数据一样多,应该是整个文件。你已经设法从二进制文件中轻松获取数据(虽然 close()调用应该在finally块中) - 它只是将它转换为文本,这是一个坏主意。

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.

这篇关于将二进制文件读入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆