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
.
例如,假设目录“C:\工作空间\项目\目标\类”在您的类路径中。在该目录中是一个文件,例如info.properties。
How would you determine (at runtime) the absolute file path to the info.properties file, given only the string "info.properties"
?
如何(在运行时)确定信息的绝对文件路径。属性文件,只给字符串“info.properties”?
The result would be something like "C:\workspace\project\target\classes\info.properties"
.
结果会是“C:\工作空间\项目\目标类\信息.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.
为什么这个有用吗?在编写单元测试时,您可能希望访问捆绑在测试资源(src/main/resources)中的文件,但是需要使用第三方库或其他需要真实文件名而不是相对类路径引用的系统。
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 个解决方案
#1
16
Use a combination of ClassLoader.getResource() and URL.getFile()
使用ClassLoader.getResource()和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:
如果您需要一个更像windows的路径(例如。“C:\ workspace \…”),使用:
String nativeFilename = new File(file).getPath();
#1
16
Use a combination of ClassLoader.getResource() and URL.getFile()
使用ClassLoader.getResource()和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:
如果您需要一个更像windows的路径(例如。“C:\ workspace \…”),使用:
String nativeFilename = new File(file).getPath();