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()
打印所有值。但是每次我尝试将值设置为文本区域时,在文本区域中只会显示文件的最后一个值。
我想念什么?
答案 0 :(得分:3)
这里:
txtArea.setText(finalValues);
设置该区域的完整文本。删除先前存储的存储内容。
您必须收集您的输入(例如,使用StringBuilder,然后在读取所有行后,致电setText(builder.toString())
一次。
更多提示:您可以使用Files.readAllLines()。还有try-with-resources。
答案 1 :(得分:1)
GhostCat的答案是最好的。使用StringBuilder
,因为它使用较少的内存(When to use StringBuilder in Java)。或者,您可以只使用+=
而不是=
,
finalValues += in.nextLine();
=
分配一个值。+=
附加一个值(将该值组合到现有值中)。while (in.hasNextLine()) {
finalValues += in.nextLine();
}
txtArea.setText(finalValues);
答案 2 :(得分:0)
您之前是在旧文本上设置新文本,因此仅保留了最后一个,请尝试以下操作:
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();
System.out.println(in.nextLine());
}
txtArea.setText(finalValues);
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}