我不确定出了什么问题,但打印输出仅在第二次完全从txt文件中提供信息。它第一次只会打印出我的txt文件中的第一行。希望有人可以指出我的错误。
这是我的代码:
public static void main(String[]args) {
try {
FileReader fileReader = new FileReader("data_file/Contact.txt");
BufferedReader in = new BufferedReader(fileReader);
String currentContact = in.readLine();
StringBuilder sb = new StringBuilder();
while(currentContact != null) {
StringBuilder current = sb.append(currentContact);
current.append(System.getProperty("line.separator"));
JOptionPane.showMessageDialog(null, "Contact : \n" + current);
// System.out.println("Contact:" + currentContact);
currentContact = in.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
答案 0 :(得分:1)
移动
JOptionPane.showMessageDialog(null, "Contact : \n" + current);
在while循环之外(并将其更改为使用sb
而不是current
)。只有在读取完整个文件后才会显示对话框。现在,您正在为输入文件中的每一行显示一个对话框。
顺便提一下,您可以替换它:
StringBuilder current = sb.append(currentContact);
current.append(System.getProperty("line.separator"));
用这个:
sb.append(currentContact);
sb.append(System.getProperty("line.separator"));
甚至可以在一行上完成:
sb.append(currentContact).append(System.getProperty("line.separator"));
StringBuffer.append
返回调用它的对象。这允许您将呼叫链接到append
。