Reputation: 9
The code snippet below causes this error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type FileNotFoundException
String path = "/Users/jfaig/Documents/workspace/my_array/";
BufferedReader in = new BufferedReader(new FileReader(path + "Matrix.txt"));
The path is valid because I can see the file listed with this code:
File dir = new File(path);
String[] chld = dir.list();
if(chld == null){
System.out.println("Specified directory does not exist or is not a directory.");
System.exit(0);
} else {
for(int i = 0; i < chld.length; i++){
String fileName = chld[i];
System.out.println(fileName);
}
}
I reviewed many articles about OS/X paths in Java and none solved my problem. I'm going to try it on a Windows PC to see if the problem is particular to OS/X and/or my installation of Eclipse.
Upvotes: 1
Views: 135
Reputation: 34397
Its not complaining about your file but asking you to put the handling in place if the file is not found.
If you don't want any handling done for this scenario, update your method signature with throws FileNotFoundException
e.g for main
method, you can write as below:
public static void main(String[] args) throws FileNotFoundExcetion {
If you want to handle the exception, or wrap the above code in a try{}catch(FileNotFoundException fnfe){}
block as below:
try{
File dir = new File(path);
String[] chld = dir.list();
if(chld == null){
System.out.println("Specified directory does not exist or is not a directory.");
System.exit(0);
} else {
for(int i = 0; i < chld.length; i++){
String fileName = chld[i];
System.out.println(fileName);
}
}
}catch(FileNotFoundException fnfe){
//log error
/System.out.println("File not found");
}
Upvotes: 3
Reputation: 23768
Let Java do the file separators with the path and use File constructor with two arguments.
File path = new File("/Users/jfaig/Documents/workspace/my_array");
File file = new File(path, "Matrix.txt");
System.out.println("file exists=" + file.exists()); // debug
BufferedReader in = new BufferedReader(new FileReader(file));
And as mentioned previously you need to catch or have the method throw IOException.
Upvotes: 0
Reputation: 13934
java.lang.Error: Unresolved compilation problem:
means that the real error is listed during the output of javac
, but it repeats it here for you. Unhandled exception type FileNotFoundException
— exceptions in Java must be explicitly caught, or re-thrown.
Upvotes: 0
Reputation: 5932
FileNotFoundException is a checked exception and needs to be handled. It has nothing to do with the file or path.
http://www.hostitwise.com/java/java_io.html
Upvotes: 6