1

My problem right now is: In my text file I get some funky looking characters when trying to use ObjectOutputStream to write my object to my cases.txt file.

    FileOutputStream file = new FileOutputStream("/cases.txt");
    ObjectOutputStream data = new ObjectOutputStream(file);

    DefectProduct s1 = new DefectProduct("test", 5, "test", "test",
            "test", 50, 2019, 1, 24, "505", "test" );
    data.writeObject(s1);

    data.flush();
    data.close();
    System.out.println("Record added");

For now I'm trying to get the part of writing my object to a textfile to work. I read somewhere that ObjectOutputStream was the choice for writing objects to text files. Is this correct?

In the end my goal is to take a whole arraylist of objects and write the whole arraylist to my text file at once.

Freddy
  • 137
  • 2
  • 10
  • Read the second sentence from the documentation for [`ObjectOutputStream`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/ObjectOutputStream.html), you'll see it's not made to be then read with a text editor. – Federico klez Culloca Dec 05 '19 at 13:16
  • Also, see [this](https://stackoverflow.com/questions/7290777/java-custom-serialization) question to try and solve your problem. – Federico klez Culloca Dec 05 '19 at 13:19
  • @FedericoklezCulloca I dont see in that example where they use a text file. – Freddy Dec 05 '19 at 13:28
  • There's a link to [this guide](https://www.oracle.com/technical-resources/articles/java/javaserial.html) that explains how serialization works and how it can be customized. That is, you can keep on using `ObjectOutputStream`, but you have to implement your custom `writeObject` method. – Federico klez Culloca Dec 05 '19 at 13:40
  • Maybe [this other answer](https://stackoverflow.com/a/12963580/133203) is a bit more clear about that. – Federico klez Culloca Dec 05 '19 at 13:41

1 Answers1

1

ObjectOutputStream does not produce human readable stream (i.e. you cannot open it in a text editor and to expect to read the content). The text editor is trying to show everything in the file as text but the file itself does not contain valid text and that's why the text editor shows unreadable characters.

The purpose of ObjectOutputStream is to generate data which later can be read back using ObjectInputStream but no one says this data will be valid text data.

It does not matter that your output file is cases.txt. The extension of the file is just part of the name and a hint to the user or the operating system what might be inside that file but this means nothing about what really is saved in this file. You can name your output file cases.mp3 but this will not produce music file.

plamkata__
  • 729
  • 5
  • 13