简体   繁体   English

Java:无法解析文件

[英]Java: file cannot be resolved

the following code is returning the following error message: 以下代码返回以下错误消息:

package demo3;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class App {
    public static void main(String[] args) {
        try {
            openFile();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            System.out.println("File not found: " + file.toString());
    }
}

public static void openFile() throws FileNotFoundException {
    File file = new File("test.txt");

    FileReader fr = new FileReader(file);
}

}

Error: 错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
file cannot be resolved

at demo3.App.main(App.java:13)

I'm not sure whether this is because the file is in a different class to the try catch loop or if it's caused by something else. 我不确定这是因为文件与try catch循环不在同一个类中,还是由其他原因引起的。 Any help would be much appreciated. 任何帮助将非常感激。 Thanks 谢谢

Instead of handling the FileNotFound exception in your main method, handle it in your openFile() method. 与其在main方法中处理FileNotFound异常,不如在openFile()方法中处理它。

Right now you're trying to access the file method where the variable has not been defined. 现在,您正在尝试访问尚未定义变量的file方法。 The file variable has only been defined in the openFile() method. file变量仅在openFile()方法中定义。

You can also define it above your main method. 您也可以在main方法上方定义它。 If you do that, every method in your class will have access to it. 如果这样做,则您班上的每个方法都可以访问它。

Either solution will solve your problem. 两种解决方案都可以解决您的问题。 Choose the one that best fits your needs. 选择最适合您的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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