ObjectOutputStream writing extra characters

时光怂恿深爱的人放手 提交于 2019-12-07 05:13:29

问题


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();
    }

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


回答1:


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".

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") ) );



回答2:


outputStream.txt file contains the binary (stream) format of your "SomeObject" as in Object Serialization. This can be read back as your original object using ObjectInputStream.This is called de-serialization process.

However, BufferedWriter write the data in text format has nothing to do with serialization. So while reading back you need to read the text and you have to re-create your object manually.




回答3:


An ObjectOutputStream writes binary data.

From the API:

public void writeUTF(String str) throws IOException

Primitive data write of this String in modified UTF-8 format.

The extra bytes are probably coming from the modified UTF-8 encoding.



来源:https://stackoverflow.com/questions/22376783/objectoutputstream-writing-extra-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!