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.
InputStream in = this.getClass().getClassLoader().getResourceAsStream("SomeTextFile.txt"); InputStream in = this.getClass().getClassLoader().getResourceAsStream("/SomeTextFile.txt"); InputStream in = this.getClass().getClassLoader().getResourceAsStream("//SomeTextFile.txt");
You have 3 solutions: add this class in the path of your other compiled classes (respecting the package naming of your directories) add the root directory of this class in your classpath (in your case "C:\java\project\") add this single class into a jar and add this jar to the classpath.
In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass(). getClassLoader().
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With