java - 将字节转换为字符串再转换为字节

标签 java string byte

我尝试从“bytefile”读取字节,将其更改为字符串并将其存储到“stringfile”。下面的代码是我的执行方式。

    PrintWriter writer = new PrintWriter(new FileOutputStream(new File("stringfile"), true));
    RandomAccessFile file = new RandomAccessFile("bytefile", "r");
    byte[] b = new byte[(int)file.length()];
    file.readFully(b);
    String str = new String(b, StandardCharsets.UTF_8);
    writer.write(str);
    writer.close();

然后我尝试将“stringfile”中的字符串转换为字节并存储在“newbytefile”中。然而结果并没有达到我的预期。

    String charset = "UTF-8";
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("stringfile"), charset));
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream("newbytefile"), charset));
    String line;
    while ((line = reader.readLine()) != null){
        writer.println(line.getBytes());
    }
    reader.close();
    writer.close();

“bytefile”中的模式是这样的:

<9e>zgóoG^P$@0<81>^B*É^X¿uú<9b>^@

“stringfile”中的模式是这样的:

�zg�oG^P$@0�^B*�^X�u��^@�� V�

但是,“newbytefile”中的模式是这样的:

[B@40226788

如何将“stringfile”中的字符串转换为与“bytefile”中原始模式相同的字节?

最佳答案

问题是:PrintWriter 没有方法来写入 byte[] 数组。

因此,当您调用 println(getBytes()) 时...编译器会尝试查找匹配的重载方法。它将找到 println(Object) (因为:最终,任何 java 数组也是一个对象)。

你可以看到使用javap反汇编器:

invokevirtual #22 // Method java/io/PrintWriter.println:(Ljava/lang/Object;)V

在该方法中,对传入对象调用 toString()。当您在字节数组上调用 toString() 时,您会得到类似于“[B....”的结果 - 请参阅 here为什么会这样。

换句话说:由于重载,您不会打印字节数组本身,而是打印该字节数组的默认字符串表示形式。

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

相关文章:

java - 如何从列表中获取不同的元素?

java - BestPractices : Is it bad OOP to subclass standard classes into a new one that does same thing, 但 "presuming" future 有变化吗?

java - 使用 Spring DAO 和 Hibernate 的数据访问层。问题

java - 在 java 中初始化字节数组时,什么时候必须转换为字节?

java - 如何在Java中读回一个字节?

java - 如何在 Lucene 中覆盖单个字段中的相似性?

java - String.subString() 和 String.subSequence() 有什么区别

ios - 在 Swift 中根据 String 计算出 UILabel 的大小

java - 不区分大小写的输入和任何改进建议

language-agnostic - little-endian 系统使用哪些转换将数据转换为网络顺序?