【发布时间】:2015-12-01 13:10:32
【问题描述】:
我正在尝试将文件内容读入任何可读形式。我正在使用 FileInputStream 从文件中读取字节数组,然后尝试将该字节数组转换为字符串。
到目前为止,我已经尝试了 3 种不同的方法:
FileInputStream inputStream = new FileInputStream(file);
byte[] clearTextBytes = new byte[(int) file.length()];
inputStream.read(clearTextBytes);
String s = IOUtils.toString(inputStream); //first way
String str = new String(clearTextBytes, "UTF-8"); //second way
String string = Arrays.toString(clearTextBytes); //third way
String[] byteValue = string.substring(1, string.length() - 1).split(",");
byte[] bytes = new byte[byteValue.length]
for(int i=0, len=bytes.length; i<len; i++){
bytes[i] = Byte.parseByte(byteValue[i].trim());
}
String newStr = new String(bytes);
当我打印出每个字符串时:
1) 不打印任何内容,并且
2 & 3) 打印出很多奇怪的字符,例如:
PK!�Q���[Content_Types].xml�(����MO�@��&��f��]���pP<*���v
�ݏ�,_��i�I�(zi�N��}fڝ���h�5)�&��6Sf����c| �“�d��R�d�Eo�r��
�l��������:0Tɭ�"Э�p'䧘��tn��&�q(=X����!.��,�_�WF�L8W..... .
我希望得到任何关于如何将我的字节数组正确转换为字符串的建议。
【问题讨论】:
-
我猜你的字节数组首先不包含字符串。从您提供的内容来看,我会说那是 Word 文档,而不是 txt。要阅读 Word 文档的内容,您需要一些库,例如 Apache POI
-
您确定该文件不是 zip 文件吗?通常,当您尝试直接从 zip 文件中读取而不解压缩它时会发生这种情况。
-
我猜“第一种方式”不会打印任何内容,因为您已经读取了从
inputStream到clearTextBytes的所有内容,因此没有更多字节要读取。 -
@StackFlowed ... 文件开始
PK;) -
但这可能是解密的zip或解密的docx
标签: java byte bytearray bytearrayinputstream