我有将一些数据写入文件的方法。我用,PrintWriter
如下图BufferedWriter
FileWriter
public void writeToFile(String FileName){
PrintWriter pw = null;
try {
pw = new PrintWriter(new BufferedWriter(new FileWriter(FileName)));
for(Cars car : list){
pw.println(car.getType());
pw.println(car.getMaxSpeed());
pw.println(car.getOwner());
pw.println();
pw.flush();
}
pw.close();
}
catch(IOException ex){
System.err.println(ex);
}
}
现在我怎样才能从文件中读取这些数据?我尝试使用InputStreamReader
,BufferedReader
和FileInputStream
,但我的 NetBeans 显示一条错误消息
public void readFromFile() throws IOException {
InputStreamReader fr = null;
try {
fr = new InputStreamReader(new BufferedReader(new FileInputStream(new FileReader("c:\\cars.txt"))));
System.out.println(fr.read());
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
fr.close();
}
}
这种方法有什么问题?