如何一次打印整个文本文件而不是第二次打印出来?

时间:2013-05-25 03:45:21

标签: java io

我不确定出了什么问题,但打印输出仅在第二次完全从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();
    }
}

1 个答案:

答案 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