2015-06-14 201 views
0

这可能是一个简单的问题。扫描文本文件时遇到问题。我想扫描一个文本文件并在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"); 
      } 
     } 
+2

你觉得'return'的确如此,你为什么这么认为? –

+4

返回??真的 –

+0

如果我删除返回它显示新的JOptionPane中的每一个新行,我不希望它那样。我想要在一个JOptionPane中扫描整个文本文件。 – Pepka

回答

0

使用 while (input.hasNext()) { //scan并在每行从文件追加到Stringvariable

}`

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

+0

请阅读:http://stackoverflow.com/help/formatting – Tom

+0

感谢您提供链接@Tom – MASh

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"); 
} 
0

现在您只在JOptionPane中只显示一行。你把它显示给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(); 
    } 
}