我有这段代码,只是想把它写到一个文件中。但是当我编译它的时候,它没有显示任何错误,但是我的文件中的文本是不可读的,一些Unicode代码等等。我使用eclipse IDE。这可能是什么原因呢?
public static void main(String[] args) {
String s = "Hello world!";
int i = 143141141;
try
{
//create new file with an ObjectOutputStream
FileOutputStream out = new FileOutputStream("test.txt");
ObjectOutputStream oout = new ObjectOutputStream(out);
//write something in a file
oout.writeObject(s);
oout.writeObject(i);
//close the stream
oout.close();
//create an ObjectInputStream for the file we created before
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("test.txt"));
//read and print what we wrote before
System.out.println("" + (String) ois.readObject());
System.out.println("" + ois.readObject());
}
catch(Exception ex)
{
ex.printStackTrace();
}
}发布于 2013-06-03 19:48:21
使用ObjectOutputStream,您可以使用Serialization将对象写入文件。序列化使用编码系统,您可以在程序中正确使用ObjectInputStream来解码这些对象。但是您将无法读取序列化过程创建的文件中的信息。
发布于 2013-06-03 19:49:06
由于您使用的是ObjectOutputStream和ObjectInputStream,它将以不可读的目标代码编写,而且当您从文件中读取时,它将以对象的形式出现,
使用BufferedReader或Writer将字符串写入文件,可读
FileReader f=new FileReader(new File("test.txt"));
BufferedReader f1=new BufferedReader(f);
发布于 2013-06-03 19:47:06
你应该用PrintWriter写文本文件,ObjectOutputStream写二进制数据。
https://stackoverflow.com/questions/16895910
复制相似问题