扫描文本文件

Scanning a text file

这可能是一个简单的问题。我在扫描文本文件时遇到问题。我想扫描一个文本文件并在 JOptionPane 中显示消息。它扫描但只显示我的文本文件的第一行,然后停止忽略其他行。如果我能得到一点帮助。非常感谢你!这是我的代码:

File file = new File("src//mytxt.txt");
           try{
               Scanner input = new Scanner(file);
               while(input.hasNext()){
                   String line = input.nextLine();
                   JOptionPane.showMessageDialog(null, line);
                   return;        
               }
               input.close();
           }
           catch (FileNotFoundException ex) {
               JOptionPane.showMessageDialog(null, "File not found");
           }
        }

如果您希望整个文件显示在一个 JOptionPane 中,则为其创建一个 StringBuilder,将每一行附加到它,然后显示它。

File file = new File("src//mytxt.txt");
try {
    Scanner input = new Scanner(file);
    StringBuilder op = new StringBuiler();
    while (input.hasNext()) {
        op.append(input.nextLine());
    }
    JOptionPane.showMessageDialog(null, op.toString());
    input.close();
}
catch (FileNotFoundException ex) {
    JOptionPane.showMessageDialog(null, "File not found");
}

现在您只显示 JOptionPane 中的一行。在将 message 显示到 JOptionPane -

之前,您必须生成 message
   File file = new File("src//mytxt.txt");
   String message = "";
   try{
       Scanner input = new Scanner(file);
       while(input.hasNext()){
           String line = input.nextLine();
           message = message+line;       
       }
       JOptionPane.showMessageDialog(null, line);
   }
   catch (FileNotFoundException ex) {
       JOptionPane.showMessageDialog(null, "File not found");
   }finally{
      input.close();
   }
}

正在使用 while (input.hasNext()) { // scan 并将每一行附加到 String variable

}`

scan 文件中的每一行并将整个文本保存在 String 变量中。 然后使用 JOptionPane.showMessageDialog(null,op) 在单个 JOptionPane.

中显示整个文本