ObjectOutputStream编写额外的字符 [英] ObjectOutputStream writing extra characters
问题描述
我知道在编写文本时应该使用作家而不是输出流,但是我仍然不明白为什么在运行该程序后文件outputStream.txt
中会有多余的字符:
I know that writers should be used instead of outputstreams when writing text, but still I don't understand why there are extra characters in the file outputStream.txt
after running this program:
public static void main(String[] args) throws FileNotFoundException, IOException
{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("C:\\Data\\tmp\\outputStream.txt")));
oos.writeObject("SomeObject");
oos.writeUTF("SomeUTF");
oos.flush();
oos.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("C:\\Data\\tmp\\outputWriter.txt")));
writer.write("SomeObject");
writer.write("SomeUTF");
writer.flush();
writer.close();
}
文件outputWriter.txt
为17字节,与预期的一样,但outputStream.txt
为28,包括一些无法识别的文本.为什么会这样?
The file outputWriter.txt
is 17bytes, as expected, but outputStream.txt
is 28, including some unrecognizable text. Why is that?
推荐答案
ObjectOutputStream
用于将Java对象写入流.这意味着不会将String的值写入流中.而是写成下一个对象是String
并且其值是SomeObject
".
ObjectOutputStream
is used to write Java objects to a stream. That means won't write the value of a String into the stream; instead if will write "the next object is a String
and the value for it is SomeObject
".
因此,如果要使用纯文本文件,则必须使用Writer
API.
So if you want a plain text file, you have to use the Writer
API.
注意:您的代码取决于平台.如果要使其独立于平台,则必须使用:
Note: Your code is platform dependent. If you want to make it platform independent, then you have to use:
FileOutputStream stream = new FileOutputStream( file );
return new BufferedWriter( new OutputStreamWriter( stream, Charset.forName("UTF-8") ) );
这篇关于ObjectOutputStream编写额外的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!