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(filen开发者_如何学JAVAame));
oos.writeObject(object);
oos.close();
}
thanks
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 with this You can get an idea how to do that.
ObjectOutputStreams are not meant for writing "text files." They are used specifically for writing an intermediate representation of Java objects out to disk. This process is known as serialization.
You most likely want to use a Writer, which is more useful for making human-readable text files. In particular, you should look at FileWriter and/or PrintWriter.
When using ObjectOutputStream
you make binary serialization of your object. You aren't supposed to view the file as a "text file" at all.
If you want to serialize your object in a human-readable way, use java.beans.XMLEncoder
. Read the linked docs on how to use it in a similar way to ObjectOutputStream
. It produces XML.
You're not writing text to the file, you're writing objects to it, which means you get a stream header, type information and internal structure. To write text, use a Writer:
Writer w = new OutputStreamWriter(new FileOutputStream(filename), encoding);
精彩评论