Reputation: 5256
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.
Upvotes: 13
Views: 7358
Reputation: 5256
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();
Upvotes: 18