Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObjectOutputStream writing extra characters

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?

like image 854
Luis Sep Avatar asked Mar 13 '14 11:03

Luis Sep


People also ask

What are the requirements for a class that you want to serialize with ObjectOutputStream?

Classes that are eligible for serialization need to implement a special marker interface, Serializable. Both ObjectInputStream and ObjectOutputStream are high level classes that extend java. io. InputStream and java.

Do you need to close ObjectOutputStream?

If you don't use it anymore, then you should definitely close it as soon as possible.

Why do we use ObjectOutputStream?

An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be read (reconstituted) using an ObjectInputStream. Persistent storage of objects can be accomplished by using a file for the stream.


1 Answers

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") ) );
like image 100
Aaron Digulla Avatar answered Oct 23 '22 11:10

Aaron Digulla