Using FileReader causes a compiler error “unhandled exception type FileNotFoundException”

后端 未结 6 1019
傲寒
傲寒 2021-01-15 10:01

Ive read a few threads here that relate the same problem, but the solutions arent working. :/

I use Eclipse, here is my program.

package mypackage;
         


        
6条回答
  •  旧巷少年郎
    2021-01-15 10:52

    I see that you tried to specify the full path to your file, but failed because of the following mistake:

    you haven't declared or tried to catch java.io.FileNotFoundException.

    To fix it, you can replace the line

    FileReader fr = new FileReader("myscript.abc");
    

    with the code:

    try {
        FileReader fr = 
        new FileReader("/home/jason/workspace/myproject/src/mypackage/myscript.abc");
    } catch (FileNotFoundException ex) {
        Logger.getLogger(myclass.class.getName()).log(Level.SEVERE, null, ex);
    }
    

    The following code is successfully compiled, and it should work:

    package mypackage;
    import java.io.*;
    // It's better to use Camel style name for class name, for example: MyClass.
    // In such a way it'll be easier to distinguish class name from variable name.
    // This is common practice in Java.
    public class myclass {
    
        public static void main(String[] args) {
            String myfile = 
                "/home/jason/workspace/myproject/src/mypackage/myscript.abc";
    
            File file1 = new File(myfile);
            if (file1.exists()) {
                log("File " + myfile + " exists. length : " + myfile.length());
            } else {
                log("File " + myfile + " does not exist!");
            }
    
            try {
                FileReader fr = new FileReader(myfile);
            } catch (FileNotFoundException ex) {
                // Do something with mistake or ignore
                ex.printStackTrace();
            }
    
            log("\nAbsPath : " + new File(".").getAbsolutePath());
            log("\nuser.dir : " + System.getProperty("user.dir"));
        }
    
        public static void log(String s) {
            System.out.println(s);
        }
    }
    

提交回复
热议问题