扫描文本文件

Pep*_*pka 0 java java.util.scanner

这可能是一个简单的问题.我在扫描文本文件时遇到问题.我想扫描一个文本文件并在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");
           }
        }
Run Code Online (Sandbox Code Playgroud)

Uma*_*nth 5

如果您希望将整个文件显示在一个文件中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");
}
Run Code Online (Sandbox Code Playgroud)