【问题标题】:ObjectOutputStream writing extra charactersObjectOutputStream 写入额外字符
【发布时间】:2014-04-18 01:53:21
【问题描述】:

我知道在写文本的时候应该使用writers而不是outputstreams,但是我还是不明白为什么运行这个程序后outputStream.txt文件中有多余的字符:

public static void main(String[] args) throws FileNotFoundException, IOException
    {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("C:\\Data\\tmp\\outputStream.txt")));
        oos.writeObject("SomeObject");
        oos.writeUTF("SomeUTF");
        oos.flush();
        oos.close();
        BufferedWriter writer = new BufferedWriter(new FileWriter(new File("C:\\Data\\tmp\\outputWriter.txt")));
        writer.write("SomeObject");
        writer.write("SomeUTF");
        writer.flush();
        writer.close();
    }

文件outputWriter.txt 是 17 字节,正如预期的那样,但 outputStream.txt 是 28,包括一些无法识别的文本。这是为什么呢?

【问题讨论】:

    标签: java file outputstream writer


    【解决方案1】:

    outputStream.txt 文件包含“SomeObject”的二进制(流)格式,如在对象序列化中。可以使用 ObjectInputStream 将其作为原始对象读回。这称为反序列化过程。

    但是,BufferedWriter 以文本格式写入数据与序列化无关。因此,在回读时,您需要阅读文本,并且必须手动重新创建对象。

    【讨论】:

    • 有什么办法可以去掉那些多余的字节..?
    • 你为什么要这样做,反正这似乎是一个不同的问题?请作为一个新问题提出。
    【解决方案2】:

    ObjectOutputStream 用于将 Java 对象写入流。这意味着不会将 String 的值写入流;相反,如果会写“下一个对象是String,它的值是SomeObject”。

    所以如果你想要一个纯文本文件,你必须使用Writer API。

    注意:您的代码取决于平台。如果你想让它独立于平台,那么你必须使用:

        FileOutputStream stream = new FileOutputStream( file );
        return new BufferedWriter( new OutputStreamWriter( stream, Charset.forName("UTF-8") ) );
    

    【讨论】:

      【解决方案3】:

      ObjectOutputStream 写入二进制数据。

      来自 API:

      public void writeUTF(String str) throws IOException
      

      以修改后的 UTF-8 格式写入此字符串的原始数据。

      额外的字节可能来自修改后的 UTF-8 编码。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-05-31
        • 1970-01-01
        • 2020-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-06
        相关资源
        最近更新 更多