Question

I am trying to load a file called SPY.txt into an array, but I can't even get this little snippet to work.

I don't understand. If f.exists is true, how can the Scanner throw a file not found exception?

import java.io.*;
import java.util.Scanner;

public class ScannerTest {
    public static void main(String[] args) {
        File f = new File (new File("SPY.txt").getAbsolutePath());
        System.out.println(f.exists());
        Scanner s = new Scanner(f);
    }
}

Output: True

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown at scannertest.ScannerTest.main(ScannerTest.java:13)

Line 13 is

Scanner s = new Scanner(f);

Was it helpful?

Solution

The clue is in the error message:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown at scannertest.ScannerTest.main(ScannerTest.java:13)

What it means is that Scanner constructor throws an exception, so you need to place it in try/catch block, like so:

import java.io.*;
import java.util.Scanner;

public class ScannerTest {
    public static void main(String[] args) {
        //try block starts here
        try {  
            File f = new File (new File("SPY.txt").getAbsolutePath());
            System.out.println(f.exists());
            Scanner s = new Scanner(f);
        } 
        //catch the exception
        catch(FileNotFoundException e) {
            e.printStackTrace();   
        }

    }
}

Check the docs here and here

OTHER TIPS

FileNotFoundException is a checked exception that's thrown by that particular Scanner constructor. Either declare it with a throws clause, or put a try-catch block in there.

This has nothing to do with whether the file exists or not, but everything to do with exception handling in Java.

You are not getting an exception that the file is not found, you are getting an error about Uncompilable source code because you didn't handle an exception.

You have "Unhandled exception type FileNotFoundException" in:

new Scanner(f)

Solutions:

  1. Surround with try-catch.
  2. Declare main to throw FileNotFoundException.

//1
try {
    File f = new File (new File("SPY.txt").getAbsolutePath());
    System.out.println(f.exists());
    Scanner s = new Scanner(f);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

OR

//2
public static void main(String[] args) throws FileNotFoundException {
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top