我想用字符串写一个文件,然后阅读它。但是当我看到它看起来与广场和东西奇怪..我不能复制粘贴!试图阅读文件
下面是代码:
import java.io.*;
public class ObjectOutputStreamDemo {
public static void main(String[] args) throws ClassNotFoundException {
try {
//Now Im writing
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("fruit.dat"));
String ord[] = { "Banana", "Mango", "Apple", "Passionfruit","Orange" };
for (int i = 0; i < 5; i++) {
output.writeObject(ord[i]);
}
output.close();
//Now Im trying to read.
BufferedReader in = new BufferedReader(new FileReader("fruit.dat"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
} catch (IOException e) {
System.out.println("Problem with file.");
}
}
}
简短回答:如果您打算使用ObjectOutputStream写入文件,则应该使用ObjectInputStream而不是BufferedReader **来读取文件。相反,如果您想要使用'Reader'读取文件,您应该使用'Writer'编写文件。 – 2011-12-20 12:12:35