ayushgp
ayushgp

Reputation: 5101

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.). 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());

Upvotes: 0

Views: 516

Answers (1)

Hülya
Hülya

Reputation: 3433

getClass().getResource() loads resources from the classpath, not from filesystem. Class loaders are responsible for loading Java classes and resources during runtime dynamically to the JVM (Java Virtual Machine).

I would suggest using 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();
    }

Upvotes: 1

Related Questions