【发布时间】:2019-12-04 07:44:46
【问题描述】:
我的项目结构如下:
src/test/resources/utility/configuration.xml
我正在尝试使用 ClassLoader 获取系统中的文件位置
public File getFileFromResources(String fileName){
ClassLoader classLoader = getClass().getClassLoader();
URL resource = classLoader.getResource(fileName);
if(resource == null){
throw new IllegalArgumentException("file not found");
}else{
return new File(resource.getFile());
}
调用方法:
File file = getFileFromResources("Utility/ConfigurationXML.xml");
strFilePath = file.getAbsolutePath();
这给了我文件的绝对路径,它位于目标文件夹中。
上面的代码在eclipse IDE中运行良好,但是当我创建项目JAR时,getFileFromResources()返回给我
file:/C:/Users/UserName/Desktop/ExecutableJAR/TestJAR-tests.jar!/Utility/ConfigurationXML.xml
我正在使用 Maven 构建我的项目。
【问题讨论】:
-
和 file:/C:/Users/UserName/Desktop/ExecutableJAR/TestJAR-tests.jar!/Utility/ConfigurationXML.xml 不好,因为... ?您可能想添加一个实际问题。
-
资源不是文件。它们位于 JAR 或 WAR 文件中。您已经有了获取资源 URL 的代码,并且可以从中获取输入流。这就是你所需要的。
-
除了@user207421 的注释之外,如果安装了适当的
FileSystem,您可以将URL转换为Path。普通文件(默认文件系统)、jar/zip 文件和模块映像就是这种情况,但对于 jar/zip 文件,您必须首先显式创建文件系统。另见this answer。但对于大多数目的,打开输入流或直接将URL传递给例如XML解析器,已经足够了。
标签: java maven classloader filepath executable-jar