0

This program that I adapted from one of the Java books I have won't display the selected file from the file chooser in the console:

import javax.swing.JFileChooser;
import java.util.Scanner;

public static void main(String[] args) throws Exception{
   JFileChooser fileChooser = new JFileChooser();
   if (fileChooser.showOpenDialog(null) 
           == JFileChooser.APPROVE_OPTION) {              

   // Get the selected File
   java.io.File file = fileChooser.getSelectedFile();

   // Create new scanner file.
       Scanner in = new Scanner(System.in); 

   // 
           while (in.hasNext()) {
               System.out.println(in.nextLine());
               System.out.println("Hello");
            }
   // Close file
           in.close();
        }

       else {
       System.out.println("No File Selected.");
   }
}
2
  • 1
    Your code doesnt compile - youre missing a class declaration
    – Reimeus
    Jan 18, 2014 at 0:58
  • Why are you using a rich client file chooser yet sending output to the console? Since JTextComponent has a read(..) method, it would be simpler and more robust to keep it all 'rich client'. Jan 18, 2014 at 1:09

2 Answers 2

1

This isn't working because you are not using the file obtained from the JFileChooser. Try changing:

   Scanner in = new Scanner(System.in); 

To

   Scanner in = new Scanner(file); 
2
  • Thank you! Is that because the scanner class is shifted only for the file, and not input on the keyboard? Jan 18, 2014 at 9:02
  • When you write new Scanner(System.in) you are passing Scanner an InputStream which is located in the System class. However in your example that's not what you wanted to use it for, so you needed to pass it the right object, which, in this case, was the File object you just obtained from JFileChooser. I hope that makes sense, feel free to ask for clarification if anything doesn't make sense.
    – facetoe
    Jan 18, 2014 at 14:03
1

You need to use the selected file as the Scanner source rather than the system InputStream

Scanner in = new Scanner(file);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.