try {
String fileName = " ";
// FileReader reads text files in the default encoding.
FileReader reader = new FileReader(fileName);
// read as strings
Scanner in = new Scanner(reader);
String finalValues = "";
while (in.hasNextLine()) {
finalValues = in.nextLine();
txtArea.setText(finalValues);
System.out.println(finalValues);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
上面的代码是将文件中的所有值读取到文本区域。抱歉,我没有将实际的文件名放在那里。我可以使用 System.out.println() 打印出所有值。但每次我尝试将值设置到文本区域时,文本区域中仅显示文件的最后一个值。
我错过了什么?
最佳答案
这里:
txtArea.setText(finalValues);
设置该区域的完整文本。删除您之前调用时存储的所有内容。
您必须收集您的输入(例如使用StringBuilder,然后在读取所有行后,调用setText(builder.toString())
一次.
更多提示:有Files.readAllLines()你可以使用的。和try-with-resources以及。
关于java - 在 Java 中将文件值读取到文本区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52420137/