spencerlarry spencerlarry - 5 months ago 11
Java Question

Throws FileNotFoundException when creating scanner from file

I'm trying to show a file open dialog and then create a scanner to read the selected file. When I run my code it throws a

FileNotFoundException
which doesn't make sense to me since it throws the exception before it opens the file selector window.

package files;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class FileManipulations {

public static void main (String[] args) {
SwingUtilities.invokeLater(() -> runGUI());
}

public static void runGUI () {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File file = chooser.getSelectedFile();
System.out.println(file.exists());
Scanner fromFile = new Scanner(file);
}
}

Answer

Starting with your example code...

import java.io.File;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;

public class FileManipulations {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> runGUI());
    }

    public static void runGUI() {
        JFileChooser chooser = new JFileChooser();
        chooser.showOpenDialog(null);
        File file = chooser.getSelectedFile();
        System.out.println(file.exists());
        Scanner fromFile = new Scanner(file);
    }
}

You are getting a compiler error because Scanner(File) can throw a FileNotFoundException

You either need to catch the exception or re-throw it, for example...

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;

public class FileManipulations {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> runGUI());
    }

    public static void runGUI() {
        JFileChooser chooser = new JFileChooser();
        switch (chooser.showOpenDialog(null)) {
            case JFileChooser.APPROVE_OPTION:
                File file = chooser.getSelectedFile();
                System.out.println(file.exists());
                try (Scanner fromFile = new Scanner(file)) {
                    while (fromFile.hasNextLine()) {
                        String text = fromFile.nextLine();
                        System.out.println(text);
                    }
                } catch (FileNotFoundException exp) {
                    exp.printStackTrace();
                }
                break;
        }
    }
}

You might also like to have a look at How to Use File Choosers and make sure you are checking the return result of showOpenDialog so you know how the dialog was closed

Also, have a look at The try-with-resources Statement for more details about how to manage your resources

Comments