许多从资源文件夹读取文件的教程都使用类加载器。但是,使用该方法我无法解决静态警告问题,结果始终是空指针异常。
public class Test {
public static void main(String[] args) {
StringBuilder contentBuilder=new StringBuilder();
ClassLoader classLoader=Test.class.getClassLoader();
File file=new File(classLoader.getSystemResource("test.html").getFile());
try {
BufferedReader buffer=new BufferedReader(new FileReader(file));
String sCurrentLine="";
while ((sCurrentLine=buffer.readLine())!=null) {
contentBuilder.append(sCurrentLine);
}
buffer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
String content=contentBuilder.toString();
System.out.println("content="+content);
}
}
我的 IDE 在"file"行的警告是:
The static method getSystemResource(String) from the type ClassLoader should be accessed in a static way
我不知道如何消除警告,如果我只是忽略它并运行代码,我会得到一个空指针异常。为什么我会得到这个以及如何解决它? TIA。
最佳答案
Test.class.getClassLoader();
从 Class
的方法 public ClassLoader getClassLoader 获取对
- 请参阅下面的 ClassLoader
类的引用()private final ClassLoader classLoader
。
因为您是从该类的对象访问 ClassLoader
类,所以您不是以静态方式访问它。
来自 Class.java
,Java SE 1.7:
@CallerSensitive
public ClassLoader getClassLoader() {
ClassLoader cl = getClassLoader0();
if (cl == null)
return null;
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
ClassLoader.checkClassLoaderPermission(cl, Reflection.getCallerClass());
}
return cl;
}
// Package-private to allow ClassLoader access
ClassLoader getClassLoader0() { return classLoader; }
// Initialized in JVM not by private constructor
// This field is filtered from reflection access, i.e. getDeclaredField
// will throw NoSuchFieldException
private final ClassLoader classLoader;
为了以静态方式访问该方法,如果您想摆脱警告,必须从将其声明为静态的类中调用它:
ClassLoader.getSystemResource("test.html").getFile()
为避免 NPE,test.html
文件应位于您的源文件夹下。
要回复您的评论,请使用返回 URL
以外的方法解决您的问题 - 请参阅 Reading a resource file from within jar .
public class Test {
public static void main(String[] args) {
StringBuilder contentBuilder = new StringBuilder();
InputStream is = Test.class.getResourceAsStream("/test.html");
try {
String sCurrentLine;
BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
while ((sCurrentLine = buffer.readLine())!=null)
contentBuilder.append(sCurrentLine);
buffer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
System.out.println("content=" + contentBuilder.toString());
}
}
关于java - 如何从资源文件夹中正确获取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51176271/