简体   繁体   中英

Opening a file in Java on OS/X

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.

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

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 eg 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");
 }          

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM