无法读取maven jar中的资源文件

时间:2017-08-18 20:27:06

标签: java maven jar

我有一个小型的maven项目。

项目结构如下:

src
  |-main
    |-java
      |-com.my.group
        S3FileUploader
    |-resources
      s3.properties

pom文件如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.my.group</groupId>
    <artifactId>try-s3</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk</artifactId>
            <version>1.11.141</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>*</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <archive>
                                <manifest>
                                    <mainClass>
                                        com.my.group.S3FileUploader
                                    </mainClass>
                                </manifest>
                            </archive>
                            <descriptorRefs>
                                <descriptorRef>jar-with-dependencies</descriptorRef>
                            </descriptorRefs>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

我的目标是: 1.将/ src / main / resources目录下的文件包含在jar包中。 2.将S3FileUploader作为主类。 / src / main / resources目录下有一个s3.properties文件。

在我的代码中,我尝试使用以下方法读取属性文件:

String propertiesFile = "s3.properties";
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            File file = new File(classLoader.getResource(propertiesFile).getFile());
            InputStream input = new FileInputStream(file);

但是运行java -jar命令会出现此错误:

java.io.FileNotFoundException: file:/try-s3-1.0-SNAPSHOT-jar-with-dependencies.jar!/s3.properties (No such file or directory)

我的问题是: 我是否以错误的方式包装罐子? 2.如果没有,在代码中如何处理以读取s3.properties文件?

提前致谢:)

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

URL url = this.getClass().getResource("file.ext")
File file = new File(url.toURI());