4

Right now, I have a set class path, but I want to have an open file pop up and the user chooses which file to open. I've tried JFileChooser, but haven't been successful so far. Here's my code:

public static void main(String[] args) throws IOException {


    JFileChooser chooser = new JFileChooser();

            int returnValue = chooser.showOpenDialog( null ) ;
    if( returnValue == JFileChooser.APPROVE_OPTION ) {
        File file = chooser.getSelectedFile() ;
    }

    // I don't want this to be hard-coded:
    String filePath = "/Users/Bill/Desktop/hello.txt";

How should I go about doing this?

Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
lrvilnius
  • 107
  • 1
  • 3
  • 8

1 Answers1

6

I think the problem is the scope of File file.

Try Declaring file outside the if-block.

 File file = null;
 if( returnValue == JFileChooser.APPROVE_OPTION ) {
        file = chooser.getSelectedFile() ;
 }
 if(file != null)
 {
      String filePath = file.getPath();
 } 
Bala R
  • 107,317
  • 23
  • 199
  • 210
  • I also need to read the file using the declaration ReadFile files = new ReadFiles(***); what should go into the ***? – lrvilnius May 22 '11 at 22:59
  • @Irvilnius What is `ReadFile`? To read a file, you can use `FileInputStream`. This [post](http://www.java-tips.org/java-se-tips/java.io/how-to-read-file-in-java.html) has an example. – Bala R May 22 '11 at 23:05