13

How would I convert the name of a file on the classpath to a real filename?

For example, let's say the directory "C:\workspace\project\target\classes" is on your classpath. Within that directory is a file, such as info.properties.

How would you determine (at runtime) the absolute file path to the info.properties file, given only the string "info.properties"?

The result would be something like "C:\workspace\project\target\classes\info.properties".

Why is this useful? When writing unit tests, you may want to access files bundled in your test resources (src/main/resources) but are working with a third-party library or other system that requires a true filename, not a relative classpath reference.

Note: I've answered this question myself, as I feel it's a useful trick, but it looks like no one has ever asked this question before.

1 Answer 1

18

Use a combination of ClassLoader.getResource() and URL.getFile()

URL url = Thread.currentThread().getContextClassLoader().getResource( resource );
if( url == null ){
    throw new RuntimeException( "Cannot find resource on classpath: '" + resource + "'" );
}
String file = url.getFile();

Note for Windows: in the example above, the actual result will be

"/C:/workspace/project/target/classes/info.properties"

If you need a more Windows-like path (i.e. "C:\workspace\..."), use:

String nativeFilename = new File(file).getPath();
5
  • 5
    what will this produce if the resource is inside a jar?
    – radai
    Jan 4, 2013 at 17:47
  • 1
    @radai here's an example of the result for a file in a jar: file:/C:/tools/some/path/jarfile.jar!/internal/path/file.txt. To find such a file using the answer above, you have to supply a path relative to the jar root - ie. "internal/path/file.txt"
    – GreenGiant
    Jan 4, 2013 at 17:53
  • @radai Also check this
    – Roman C
    Jan 4, 2013 at 18:11
  • Just plain awesome. You mention Windows in your answer, but I just ran it on Linux no problem.
    – demongolem
    Jul 2, 2013 at 3:31
  • 1
    This does not work for filenames with non-URL-safe characters in them - like spaces - because they will be percent-encoded in the return value of getFile. Apr 19, 2016 at 14:25

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.