5

I am running the following code

package test.commons;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class Try_FileUtilsWrite {

    public static void main(String[] args) throws IOException {
        System.out.println(FileUtils.class.getClassLoader());
        FileUtils.write(new File("output.txt"), "Hello world");
    }

}

and getting

Exception in thread "main" java.lang.NoSuchMethodError: org.apache.commons.io.FileUtils.write(Ljava/io/File;Ljava/lang/CharSequence;)V
    at test.commons.Try_FileUtilsWrite.main(Try_FileUtilsWrite.java:12)

apparently, an old version of commons io used somewhere. But I don't see it in the project.

Is it possible to know the path to class file at runtime?

Suzan Cioc
  • 26,725
  • 49
  • 190
  • 355

1 Answers1

10

Yes you can use that Classloader to get the resource from which the class is loaded:

ClassLoader classLoader = FileUtils.class.getClassLoader();

URL resource = classLoader.getResource("org/apache/commons/io/FileUtils.class");
System.out.println(resource);

Sample output:

jar:file:/D:/maven_repository/commons-io/commons-io/2.0.1/commons-io-2.0.1.jar!/org/apache/commons/io/FileUtils.class

M A
  • 65,721
  • 13
  • 123
  • 159
  • Thanks for this. In my case, turned out I needed to run `mvn clean` on a maven module I wasn't expecting to have to clean. – Muhd Aug 12 '16 at 21:56