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());
}
}
});
~is a Shell shortcut for the home directory. Use an absolute path likeAs 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, theJFileChooserstarts in the user’s home directory – but this is true for any non-existing directory, for instanceAs 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 thatFileReader()should not throw aFileNotFoundException.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 yourFileReader()constructor: