ObjectOutputStream编写额外的字符 [英] ObjectOutputStream writing extra characters

查看:139
本文介绍了ObjectOutputStream编写额外的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在编写文本时应该使用作家而不是输出流,但是我仍然不明白为什么在运行该程序后文件outputStream.txt中会有多余的字符:

I know that writers should be used instead of outputstreams when writing text, but still I don't understand why there are extra characters in the file outputStream.txt after running this program:

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,包括一些无法识别的文本.为什么会这样?

The file outputWriter.txt is 17bytes, as expected, but outputStream.txt is 28, including some unrecognizable text. Why is that?

推荐答案

ObjectOutputStream用于将Java对象写入流.这意味着不会将String的值写入流中.而是写成下一个对象是String并且其值是SomeObject".

ObjectOutputStream is used to write Java objects to a stream. That means won't write the value of a String into the stream; instead if will write "the next object is a String and the value for it is SomeObject".

因此,如果要使用纯文本文件,则必须使用Writer API.

So if you want a plain text file, you have to use the Writer API.

注意:您的代码取决于平台.如果要使其独立于平台,则必须使用:

Note: Your code is platform dependent. If you want to make it platform independent, then you have to use:

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

这篇关于ObjectOutputStream编写额外的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆