【问题标题】:Convert byte array to String - java将字节数组转换为字符串 - java
【发布时间】: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 文件中读取而不解压缩它时会发生这种情况。
  • 我猜“第一种方式”不会打印任何内容,因为您已经读取了从 inputStreamclearTextBytes 的所有内容,因此没有更多字节要读取。
  • @StackFlowed ... 文件开始 PK ;)
  • 但这可能是解密的zip或解密的docx

标签: java byte bytearray bytearrayinputstream


【解决方案1】:

正如其他人所指出的,数据看起来不包含任何文本,因此很可能是二进制数据,而不是文本。注意以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;
}

【讨论】:

  • 太棒了——我已经把它做成了一个拉链并打开了它。但是,当我输出字符串而不是输入时,我对检查编码是什么以及检查损坏不是什么意思感到有点困惑。那么您的 possibleCharsets 函数是否应该返回所有不包含 � 的字符集,然后我从中创建一个新字符串?抱歉,我对字节/二进制数据/ascii 的东西还很陌生。
  • (另外,最初我试图阅读的 Word 文档是一个简单的 .docx)
  • @KevinDonahoe docx 文件格式并不简单;)您需要一个设计用于阅读此类文档的库,以便有机会阅读它。由于它是二进制格式,因此不适用字符编码。
【解决方案2】:

UTF8 可以容纳大约 2,097,152 个不同的字符,他们没有图像你看到问号。请尝试使用经典的 dos 代码页:

new String(clearTextBytes, "DOS-US");

【讨论】:

    【解决方案3】:

    查看此内容以获取 word 文件的文本内容:您需要 Apache POI 库。

    import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
    import org.apache.poi.xwpf.usermodel.XWPFDocument;
    
    [...]
    
       XWPFDocument docx = new XWPFDocument(new FileInputStream("file.docx"));       
       XWPFWordExtractor we = new XWPFWordExtractor(docx);
       System.out.println(we.getText());
    

    【讨论】:

      【解决方案4】:

      我编写了一个非常基本的程序来读取文件的内容并在控制台的新行上打印每个字符串。这是文件的内容:

      这是我写的程序:

      import java.io.*;
      import java.util.*;
      
      class Test {
          public static void main(String args[]) throws FileNotFoundException {
              File file = new File("File1.txt");
              Scanner input = new Scanner(file);
      
              while (input.hasNext()) {
                  System.out.println(input.next());
              }
      
              input.close();
      
          } // main()
      } // class Test
      

      这是控制台的输出:

      apples
      pears
      1
      2
      3
      oranges
      carrots
      bananas
      pineapples
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-06
        • 2013-12-19
        • 2011-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-21
        相关资源
        最近更新 更多