Convert a classpath filename to a real filename

旧巷老猫 提交于 2019-11-29 17:23:04

问题


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:


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


来源:https://stackoverflow.com/questions/14162100/convert-a-classpath-filename-to-a-real-filename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!