clifford.duke
clifford.duke

Reputation: 4030

Getting java.io.FileNotFoundException when trying to read a file

I am writing a small app that reads a csv file and displays the contents into a JList.

My current problem is that the new FileReader(file) code keeps giving me a java.io.FileNotFoundException error and I am not too sure why.

loadFile.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent actionEvent)
            {
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setCurrentDirectory(new File("~/"));

                if (fileChooser.showOpenDialog(instance) == JFileChooser.APPROVE_OPTION)
                {
                    File file = fileChooser.getSelectedFile();
                    CSVReader reader = new CSVReader(new FileReader(file.getAbsolutePath()));
                    fileLocation.setText(file.getAbsolutePath());

                }
            }
        });

Upvotes: 2

Views: 1841

Answers (2)

Andreas Fester
Andreas Fester

Reputation: 36630

new File("~/")

~ is a Shell shortcut for the home directory. Use an absolute path like

new File("/home/myself/")

As pointed out by @pickypg, JFileChooser.setCurrentDirectory() sets the user's home directory as default if the passed directory is invalid. So, even though File() does not interpret ~ as a Shell does, the JFileChooser starts in the user's home directory - but this is true for any non-existing directory, for instance

new File("/Windows")   // JFileChooser would start in "\Windows"
new File("/xWindows")   // JFileChooser would start in the user's home directory

As the documentation states, the user's home directory is system specific, but on MS Windows it is typically the "My Documents" folder.

But, even when using such an non-existing path as "~/", JFileChooser.getSelectedFile() returns a proper path, so that FileReader() should not throw a FileNotFoundException.


Based on the comments, it turns out that the issue is not a runtime exception, but a compile time error where the exception is not catched. Add a try{}catch{} block around your FileReader() constructor:

try {
    CSVReader reader = new CSVReader(new FileReader(file.getAbsolutePath()));
}catch(FileNotFoundException fnfe) {
    // handle exception, e.g. show error message
}

Upvotes: 5

pickypg
pickypg

Reputation: 22332

If the problem is actually at that line, and not where Andreas points out, then construct the FileReader directly with the file rather than giving it the path:

new FileReader(file)

Upvotes: 1

Related Questions