Scanning a text file

555 Views Asked by At

it is probably a simple question. I have a problem with scanning a text file. I want to scan a text file and to show the message in a JOptionPane. It scans but it shows only the first line of my text file and then stops disregarding the other lines. If I can get a little help. Thank you very much! Here is my code:

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

There are 3 best solutions below

1
On BEST ANSWER

Using while (input.hasNext()) { // scan and append each line to a String variable

}`

scan each line from the file and keep the whole text in a String variable. Then use JOptionPane.showMessageDialog(null,op) to show the whole text in a single JOptionPane.

0
On

If you want the whole file to be displayed in a single JOptionPane, then create a StringBuilder for it, append every line to it and then show it.

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
On

Now you are displaying only the one line in JOptionPane. You have to generate the message before displaying it to JOptionPane -

   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();
   }
}