gpt4 book ai didi

java - java读取文件错误

转载 作者:行者123 更新时间:2023-12-01 15:28:41 25 4
gpt4 key购买 nike

嗨,我一直在使用缓冲阅读器尝试读取文本文件并打印文本文件有多少行。我的代码是这样的......

File parent = new File("/Desktop/Test Folder");
File text = new File(parent, "/text.txt");
FileWriter fw;
FileReader fr;
BufferedWriter write;
BufferedReader read;
if (!parent.exists()) {
parent.mkdir();
}
try {
text.createNewFile();
} catch (Exception ex) {
System.err.println("Error creating file");
}
try {
fw = new FileWriter(text);
fr = new FileReader(text);
write = new BufferedWriter(fw);
read = new BufferedReader(fr);
} catch (Exception ex) {
System.err.println("Error trying to write or read file");
}
System.out.println("Writing to file...");
try {
write.write("String number one.\n");
write.write("String number two.\n");
List<String> lines = new LinkedList<String>();
String line = read.readLine();
while (line != null) {
lines.add(line);
line = read.readLine();
}
System.out.printf("Number of lines is %d.\n", lines.size());
write.flush();
write.close();
} catch (Exception ex) {
System.err.println("Error writing to file");
}

当我运行它时,它说列表行中有 0 个元素。有什么帮助吗?我是否在某个地方犯了无车错误或者我使用了错误的方法?我是业余爱好者,所以我怀疑这个错误是显而易见的。不管怎样,有人可以给我一些帮助吗?

最佳答案

您是否尝试将 writer.flush(); 调用移到 readLine() 调用之前?

来自documentation Writer.flush()的:

Flush the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination

因此,如果您在刷新之前阅读,您的文件可能是空的!

关于java - java读取文件错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9846778/

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