将类路径文件名转换为实际文件名 [英] Convert a classpath filename to a real filename

查看:201
本文介绍了将类路径文件名转换为实际文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将类路径上的文件名转换为真实文件名?

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

例如,假设目录C :\ workspace \ project #\\ target\\ class在您的类路径中。在该目录中是一个文件,例如 info.properties

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.

您如何确定(在运行时) info.properties文件的绝对文件路径,只给出字符串info.properties

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

结果就像C:\ workspace \project\target\classes\info.properties

为什么这有用?编写单元测试时,您可能希望访问测试资源中捆绑的文件( src / main / resources ),但是正在使用第三方库或其他需要的系统一个真正的文件名,而不是一个相对的类路径引用。

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.

推荐答案

使用ClassLoader.getResource()和URL.getFile()的组合

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

Windows注意事项:在上面的示例中,实际结果将是

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

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

如果你需要更像Windows的路径(即C:\ workspace \ ...),使用:

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

String nativeFilename = new File(file).getPath();

这篇关于将类路径文件名转换为实际文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆