try
{
File dataFile = new File("C:/Users/keatit/Desktop/players.txt");
if(!dataFile.exists())
{
dataFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream("C:/Users/keatit/Desktop/players.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(players);
oos.close();
}
catch(FileNotFoundException fnfex)
{
System.out.println(fnfex.getMessage());
}
catch(IOException ioex)
{
System.out.println(ioex.getMessage());
}
I have a class player which implement Serializable but when I write objects to files the text is messed up and looks like the following. Any help would be much appreciated. Thank you.
"¬í sr java.util.ArrayListxÒ™Ça I sizexp w sr players.playerÌ`~%×êòœ I ageL firstNamet Ljava/lang/String;xp t Trevorsq ~ t Michaelax"
This is binary serialization. It's not meant to be writing to a human-readable text file. For that, you should look into something like JSON or YAML. I'd strongly recommend against writing to a .txt
file using ObjectOutputStream
- it gives the wrong impression.
The point of binary serialization is to be able to deserialize it later with the same serialization protocol - so in this case you'd use ObjectInputStream
. You should find that that is able to correctly deserialize the object stored in your file.
(Side-note: FileOutputStream
will create a new file automatically if it doesn't exist - you don't need to do so yourself. Additionally, you should use a try-with-resources statement to clean up automatically, rather than just calling close()
outside a finally
block.)
See more on this question at Stackoverflow