简体   繁体   English

class.getResource()。getFile()获取文件的旧版本

[英]class.getResource().getFile() fetches older version of a file

I have a file in the same path under test resources package as my test class. 我的测试类在测试资源包下的路径相同。 When I try to run the test cases using ./gradlew test after making changes to the resource file, the changes are not reflected when that file is read(verified using a debugger.). 当我尝试对资源文件进行更改后使用./gradlew test运行测试用例时,在读取该文件(使用调试器验证)后,更改不会反映出来。 I've tried cleaning the project but that doesn't help. 我试过清理项目,但这无济于事。

Is there some other caching that happens for resources that I'm missing here? 对于我在这里缺少的资源,是否还有其他缓存发生?

This is how I'm reading the file: 这就是我读取文件的方式:

File testFile = new File(this.getClass().getResource("namr_two").getFile());

getClass().getResource() loads resources from the classpath, not from filesystem. getClass()。getResource()从类路径而不是文件系统中加载资源。 Class loaders are responsible for loading Java classes and resources during runtime dynamically to the JVM (Java Virtual Machine). 类加载器负责在运行时将Java类和资源动态加载到JVM(Java虚拟机)。

I would suggest using ClassLoader.getSystemResource(): 我建议使用ClassLoader.getSystemResource():

    File testFile = new File(ClassLoader.getSystemResource("namr_two").getFile());

or: 要么:

    Class class1 = null;
    try {
        class1 = Class.forName("class1");
        ClassLoader cl = class1.getClassLoader();
        File testFile = new File(cl.getResource("namr_two").getFile());
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

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

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