File not found when trying to pass user given file to new scanner object

65 views Asked by At
public void readItemData()
    {
        try {
            Frame frame = null;
            FileDialog fileBox = new FileDialog(frame ,"Open", FileDialog.LOAD);
            fileBox.setVisible(true);
            String filename = fileBox.getFile();
            System.out.println(filename);
            File inFile = new File("filename");
            System.out.println(inFile.getAbsolutePath());
            Scanner fileScanner = new Scanner(inFile);
            while ( fileScanner.hasNext() )
            {
                String line = fileScanner.next();
                System.out.println(line);
            }
        }
        catch (FileNotFoundException ex)
        {
         System.out.println("Error.");
        }
    }

The above code is supposed to take a file given by the file dialog box, then pass it to a scanner which reads the whole file. The system to take the file is working, but when passed to the scanner it always gives a file not found exception. I'm not sure how to pass it properly to the scanner and simply read line by line.

I tried using quotations marks and not, removing the try-catch, etc. I feel like it is a simple problem but I cant figure it out. There have been instances where I got it to print the name of the file, but I think that was when I passed it in quotations and it was reading as if it was a string.

2

There are 2 answers

0
k314159 On

The FileDialog.getFile() method only gives you the filename. You need to also call getDirectory() to get the directory of the file. It's likely that you were trying to get a file from a different directory than what the user selected.

Instead of calling getDirectory() and getFile() and putting them together, it would be easier to call getFiles(). This returns an array of File - it's an array because the user may have selected more than one file. If the user pressed Cancel, an empty array would be returned.

So you can do this:

        File[] files = fileBox.getFiles();
        if (files.length == 1) {
            File inFile = files[0];
            try (Scanner fileScanner = new Scanner(inFile)) {
                ... rest of your code...
            }
1
moyu-sharo On

I also see probably a mistake here:

while ( fileScanner.hasNext() )
{
    String line = fileScanner.next();
    System.out.println(line);
}

What you need here is nextLine() instead of next()

while ( fileScanner.hasNextLine() )
{
    String line = fileScanner.nextLine();
    System.out.println(line);
}