gpt4 book ai didi

java - 将字节数组转换为字符串 - java

转载 作者:行者123 更新时间:2023-11-30 06:56:51 25 4
gpt4 key购买 nike

我正在尝试以任何可读形式读入文件内容。我正在使用 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..... .

我希望得到有关如何将我的字节数组正确转换为字符串的任何建议。

最佳答案

正如其他人所指出的,数据看起来并不包含任何文本,因此它很可能是二进制数据,而不是文本。请注意,以 PK 开头的文件可能是 PKZIP 格式,并且数据的随机性表明它可能会被压缩。 http://www.garykessler.net/library/file_sigs.html尝试将文件重命名为末尾有 .ZIP,看看是否可以在文件资源管理器中打开它。

从上面的链接中,DOCX 文件的开头如下所示。

50 4B 03 04 14 00 06 00 PK...... DOCX, PPTX, XLSX

Microsoft Office Open XML Format (OOXML) Document

NOTE: There is no subheader for MS OOXML files as there is with
DOC, PPT, and XLS files. To better understand the format of these files,
rename any OOXML file to have a .ZIP extension and then unZIP the file;
look at the resultant file named [Content_Types].xml to see the content
types. In particular, look for the <Override PartName= tag, where you
will find word, ppt, or xl, respectively.

Trailer: Look for 50 4B 05 06 (PK..) followed by 18 additional bytes
at the end of the file.

假设您有文本数据,很可能字符编码不是您的默认编码,也不是 UTF-8。您需要 a) 检查编码是什么,b) 当您输出字符串而不是输入时检查是否损坏。

您可以尝试暴力查找不会产生任何未知字符的字符集。

public static Set<Charset> possibleCharsets(byte[] bytes) {
Set<Charset> charsets = new LinkedHashSet<>();
for (Charset charset : Charset.availableCharsets().values()) {
if (!new String(bytes, charset).contains("�"))
charsets.add(charset);
}
return charsets;
}

关于java - 将字节数组转换为字符串 - java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34021260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com