简体   繁体   English

在JAVA中从JAR运行时如何获取定位文件的文件路径?

[英]How to get filepath of the located file when ran from JAR in JAVA?

My project has the following structure:我的项目具有以下结构:

src/test/resources/utility/configuration.xml

I am trying to get the file location in the system using ClassLoader我正在尝试使用 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());
        }

Calling method:调用方式:

File file = getFileFromResources("Utility/ConfigurationXML.xml");
strFilePath = file.getAbsolutePath();

which gives me the absolute path of the file, which is in the target folder.这给了我文件的绝对路径,它在目标文件夹中。

The above code works fine in eclipse IDE, but when I created the project JAR, getFileFromResources() returns me上面的代码在 Eclipse IDE 中工作正常,但是当我创建项目 JAR 时, getFileFromResources()返回我

file:/C:/Users/UserName/Desktop/ExecutableJAR/TestJAR-tests.jar!/Utility/ConfigurationXML.xml

I am using Maven to build my project.我正在使用 Maven 来构建我的项目。

As your path indicates, the respurce is part of yout test resources.正如您的路径所示,资源是您测试资源的一部分。 Test resources can't be accessed by production code (while test code can access production resources).生产代码无法访问测试资源(而测试代码可以访问生产资源)。 If you need this particular resource in production, then you need to move it to your production resources folder hierarcy (that would usually be src/main/resources/utility/configuration.xml .如果您在生产中需要此特定资源,则需要将其移动到您的生产资源文件夹层次结构(通常为src/main/resources/utility/configuration.xml

Test Resources (and classes) are not included in a JAR file because that's considered production code.测试资源(和类)不包含在 JAR 文件中,因为它被视为生产代码。

As @Nicktar stated that "Test resources can't be accessed by production code"正如@Nicktar所说,“生产代码无法访问测试资源”

There's no standard for anything at the root level called resources.在称为资源的根级别没有任何标准。

src/main/resources is normally where you put non-Java artifacts that should be moved into the normal package hierarchy, like XML config files loaded as classpath resources. src/main/resources 通常是您放置应该移动到正常包层次结构中的非 Java 工件的地方,例如作为类路径资源加载的 XML 配置文件。

I have get the same problem wene using netbeans (it does'n work from command line java -jar jarname.jar )我在使用 netbeans 时遇到了同样的问题(它确实从命令行java -jar jarname.jar 工作
I end up puting my ressource file in a folder in the root of the project then after building the jar I move that folder to the same plase as the jar file.我最终将资源文件放在项目根目录的文件夹中,然后在构建 jar 后将该文件夹移动到与 jar 文件相同的位置。
and it work它工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM