2

I am facing an issue while saving a text file in Java. I have coded instructions to create a file with information I want to keep in a text file. But when I want to open it, I have an error message which says that my file was loaded with the wrong encoding (UTF-8) and I can't get back the informations I want. I have tried to reload with others encoding like ISO8859-1 (which is supposed to work in most of the cases, but it didn't.

oos = new ObjectOutputStream(
                new BufferedOutputStream(
                        new FileOutputStream(
                                new File("game.txt"))));

Then I create my objects, and then I get back my datas.

ois = new ObjectInputStream(
                new BufferedInputStream(
                        new FileInputStream(
                                new File("game.txt"))));

I didn't find any way to solve my issue. Kindly help.

Gilaway
  • 31
  • 3
  • https://stackoverflow.com/questions/1001540/how-to-write-a-utf-8-file-with-java – A Honey Bustard Jul 16 '20 at 14:47
  • @AHoneyBustard encodings are part of `Writer`, not `Stream` right? This code is only using `Stream`s. – omajid Jul 16 '20 at 14:49
  • 5
    `ObjectOutputStream` and `ObjectInputStream` are not suitable for writing and reading text files. They serialize objects to / from a binary format. Don't use them to write / read text files. – Jesper Jul 16 '20 at 14:51
  • well FileOutputStream takes an encoding parameter in one of its constructors, why dont you try that – A Honey Bustard Jul 16 '20 at 14:51
  • @AHoneyBustard: "well FileOutputStream takes an encoding parameter in one of its constructors" - I don't see any sign of that... https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/io/FileOutputStream.html – Jon Skeet Jul 16 '20 at 14:55
  • @Jon Skeet thank you, you are right I meant OutputStreamWriter not FileOutputStream – A Honey Bustard Jul 16 '20 at 15:00
  • 1
    Class [`ObjectOutputStream`](https://docs.oracle.com/javase/8/docs/api/java/io/ObjectOutputStream.html) is for serializing objects, as stated in the _javadoc_ of the class: _An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream._ Are you trying to serialize an object or are you trying to write a text file? You cannot serialize a java object to a text file. – Abra Jul 16 '20 at 16:12
  • @Abra I am trying to write into an object which is supposed to be serializable no ? And then I want to keep this object in my text file. – Gilaway Jul 17 '20 at 12:25

0 Answers0