我正在尝试使用以下代码片段访问 Eclipse 中的资源文件。
public class ResourceHandler {
public void test() throws IOException {
String filePath = this.getClass().getResource("resources/MANIFEST_HAPPYVERSION.MF").getPath();// throws a NPE
System.out.println( filePath );
//System.out.println( file.exists() );
}
public static void main(String [] args) throws Exception {
ResourceHandler test = new ResourceHandler();
test.test();
}
}
这是我的目录结构的图片。
我到底做错了什么?
最佳答案
正确的方法是使用类加载器中的 getResource。因此它可以在任何地方工作,包括 Web 容器。
URL resource = this.getClass().getClassLoader().getResource("MANIFEST_HAPPYVERSION.MF");
if (resource != null) {
String path = resource.getPath(); // You can try getFile...
}
关于java - 访问资源文件错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26520238/