Java: unwanted characters at the beginning of a file as a result of serialization

when I write a new text file in Java, I get these characters at the beginning of the file:

ยจรŒt 

This is the code:

 public static void writeMAP(String filename, Object object) throws IOException { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename)); oos.writeObject(object); oos.close(); } 

thanks

+2
source share
4 answers
 Writer output = null; String text = "Www.criandcric.com. is my site"; File file = new File("write.txt"); output = new BufferedWriter(new FileWriter(file)); output.write(text); output.close(); 

I hope you can figure out how to do this.

+3
source

ObjectOutputStreams are not intended for writing "text files." They are used specifically to write an intermediate representation of Java objects to disk. This process is known as serialization.

You will most likely want to use Writer, which is more useful for creating human-readable text files. In particular, you should look at FileWriter and / or PrintWriter .

+4
source

When using ObjectOutputStream you do binary serialization of your object. You should not view the file as a "text file" at all.

If you want to serialize your object in a human-friendly way, use java.beans.XMLEncoder . Read related documents on how to use it in the same way as ObjectOutputStream . It creates XML.

+3
source

You do not write text to a file, you write objects to it, which means that you get the stream header, type information, and internal structure. To write text, use Writer:

 Writer w = new OutputStreamWriter(new FileOutputStream(filename), encoding); 
+2
source

Source: https://habr.com/ru/post/897319/


All Articles