我有一个简单的Java程序如下:
public class HelloWorldPrinter {
String filepath;
public void setPath(String path){
this.filepath = path;
}
public static void main(String[] args) throws PrintException, IOException {
FileInputStream in = new FileInputStream(new File(filepath));
}
}
我收到以下错误:
HelloWorldPrinter.java:40: error: non-static variable filepath cannot be referenced from a static context
FileInputStream in = new FileInputStream(new File(filepath));
我该如何解决这个问题?
最佳答案
一种选择是创建 HelloWorldPrinter
的实例:
public static void main(String[] args) throws PrintException, IOException {
HelloWorldPrinter printer = new HelloWorldPrinter();
printer.setPath("path/to/file");
FileInputStream in = new FileInputStream(new File(printer.getPath()));
}
关于java - 无法从静态上下文引用非静态变量文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36281943/