gpt4 book ai didi

Java - 当我使用 PrintWriter、BufferedWriter 和 FileWriter 写入时如何从文件中读取?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:08:42 25 4
gpt4 key购买 nike

我有将一些数据写入文件的方法。我使用 PrintWriterBufferedWriterFileWriter 如下所示

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);
}
}

现在如何从文件中读取这些数据?我尝试使用 InputStreamReaderBufferedReaderFileInputStream,但我的 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();
}
}

这个方法有什么问题?

最佳答案

BufferedReader in = new BufferedReader(new FileReader("file.in"));
BufferedWriter out = new BufferedWriter(new FileWriter("file.out"));

String line = in.readLine(); // <-- read whole line
StringTokenizer tk = new StringTokenizer(line);
int a = Integer.parseInt(tk.nextToken()); // <-- read single word on line and parse to int

out.write(""+a);
out.flush();

关于Java - 当我使用 PrintWriter、BufferedWriter 和 FileWriter 写入时如何从文件中读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16135726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com