java - 如何从资源文件夹中正确获取文件

标签 java resources classloader

许多从资源文件夹读取文件的教程都使用类加载器。但是,使用该方法我无法解决静态警告问题,结果始终是空指针异常。

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.javaJava 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/

相关文章:

java - Gson接口(interface)的通用集合

java - 如何检测恶意数据包?

c# - 资源位图文件 - 不包含属性定义

java - 如何从 .jar 加载文件夹?

scala - 在 scala 2.10 中使用 typetag 获取类加载器

java - c3po 辅助线程会死锁

java - 如何使用java cdi的注入(inject)点读取非绑定(bind)属性

c# - 找不到适合指定文化或中性文化的任何资源

multithreading - tomcat类加载器性能问题

java - 通过java在运行时加载两个不同版本的jar