简体   繁体   English

FileNotFoundException启动jar-在资源文件夹中看不到文件

[英]FileNotFoundException starting jar - can't see file in resources folder

I want that my application will be OS independent. 我希望我的应用程序独立于操作系统。 Therefore my config.properties and log file are stored in resources folder and I get these resources with relative path. 因此,我的config.properties和日志文件存储在resources文件夹中,并且获得了具有相对路径的这些资源。 Here is my project structure. 这是我的项目结构。 项目结构

Here is my AppConfig class: 这是我的AppConfig类:

public final class AppConfig {

private static final String RELATIVE_PATH_TO_PROPERTIES = "./src/main/resources/config.properties";
public static final String RELATIVE_LOG_PATH = "./src/main/resources/err_action.log";

private static Properties props = initProperties();
public static final String HOST = props.getProperty("ip_address");

public static final int PORT = Integer.valueOf(props.getProperty("port"));
public static final int MAX_USERS = Integer.valueOf(props.getProperty("max_number_of_users"));
public static final int NUM_HISTORY_MESSAGES = Integer.valueOf(props.getProperty("last_N_messages"));

private static Properties initProperties() {
    Properties properties = null;
    try (FileInputStream input = new FileInputStream(RELATIVE_PATH_TO_PROPERTIES)) {
        properties = new Properties();
        properties.load(input);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return properties;
}
}

As you can see, I specify relative path for properties and log files. 如您所见,我为属性和日志文件指定了相对路径。 I create jar with maven and when I run it, I receive 我用maven创建jar,当我运行它时,我收到

java.io.FileNotFoundException: ./src/main/resources/err_action.log (No such file or directory) java.io.FileNotFoundException:./src/main/resources/err_action.log(无此类文件或目录)

UPD Here is my pom.xml UPD这是我的pom.xml

<?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>chat</groupId>
<artifactId>Client-Chat</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<properties>
    <java_version>1.8</java_version>
</properties>
<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>${java_version}</source>
                <target>${java_version}</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <archive>
                    <manifest>
                        <mainClass>nikochat.com.app.Main</mainClass>
                        <!--<mainClass>nikochat.com.app.RunClient</mainClass>-->
                    </manifest>
                </archive>
            </configuration>
        </plugin>

    </plugins>
</build>
</project>

I use Intellij Idea and run maven package command, result of which is next output: 我使用Intellij Idea并运行maven package命令,其结果是下一个输出:

[INFO] Scanning for projects... [INFO] ------------------------------------------------------------------------ [INFO] Building Unnamed - chat:Server-Chat:jar:1.0 [INFO] [INFO]正在扫描项目... [INFO] -------------------------------------- ---------------------------------- [INFO]建筑物未命名-chat:Server-Chat:jar:1.0 [信息]
task-segment: [package] [INFO] ------------------------------------------------------------------------ [INFO] [resources:resources {execution: default-resources}] [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, ie build is platform dependent! 任务段:[程序包] [信息] ---------------------------------------- -------------------------------- [INFO] [resources:resources {execution:default-resources}] [警告]使用平台编码(实际上是UTF-8)来复制过滤的资源,即构建依赖于平台! [INFO] Copying 2 resources [INFO] [compiler:compile {execution: default-compile}] [INFO] Nothing to compile - all classes are up to date [INFO] [resources:testResources {execution: default-testResources}] [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, ie build is platform dependent! [INFO]复制2个资源[INFO] [compiler:compile {execution:default-compile}] [INFO]无需编译-所有类都是最新的[INFO] [resources:testResources {execution:default-testResources}] [警告]使用平台编码(实际上是UTF-8)来复制过滤的资源,即构建依赖于平台! [INFO] skip non existing resourceDirectory /home/nikolay/IdeaProjects/Chat/src/test/resources [INFO] [compiler:testCompile {execution: default-testCompile}] [INFO] Nothing to compile - all classes are up to date [INFO] [surefire:test {execution: default-test}] [INFO] Surefire report directory: /home/nikolay/IdeaProjects/Chat/target/surefire-reports [INFO]跳过不存在的resourceDirectory / home / nikolay / IdeaProjects / Chat / src / test / resources [INFO] [compiler:testCompile {执行:default-testCompile}] [INFO]无需编译-所有类都是最新的[ INFO] [surefire:test {执行:默认测试}] [INFO] Surefire报告目录:/ home / nikolay / IdeaProjects / Chat / target / surefire-reports

------------------------------------------------------- TESTS ------------------------------------------------------- Running AppConfigTest Tests run: 2, Failures: 0, Errors: 0, Skipped: 2, Time elapsed: 0.129 sec -------------------------------------------------- -----测试-------------------------------------------- -----------运行AppConfigTest测试运行:2,失败:0,错误:0,跳过:2,经过的时间:0.129秒

Results : 结果:

Tests run: 2, Failures: 0, Errors: 0, Skipped: 2 测试运行:2,失败:0,错误:0,跳过:2

[INFO] [jar:jar {execution: default-jar}] [INFO] Building jar: /home/nikolay/IdeaProjects/Chat/target/Server-Chat-1.0.jar [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESSFUL [INFO] ------------------------------------------------------------------------ [INFO] Total time: 11 seconds [INFO] Finished at: Mon Sep 08 09:47:18 [INFO] [jar:jar {执行:默认jar}] [INFO]构建jar:/home/nikolay/IdeaProjects/Chat/target/Server-Chat-1.0.jar [INFO] -------- -------------------------------------------------- -------------- [INFO]成功建立[INFO] ---------------------------- -------------------------------------------- [INFO]总时间: 11秒[INFO]完成于:9月08日星期一09:47:18

EEST 2014 [INFO] Final Memory: 18M/154M [INFO] 2014年EEST [INFO]最终内存:18M / 154M [INFO]

at the beginning I create Server-Chat jar for running server part of application, than I change artifactId to Client-Chat and manifest mainClass to create client part of application. 在开始时,我创建了Server-Chat jar来运行应用程序的服务器部分,然后将artifactId更改为Client-Chat并显示mainClass来创建应用程序的客户端部分。 Both parts I run in terminal typing command: java -jar Server-Chat-1.0.jar or java -jar Client-Chat-1.0.jar respectively. 我在终端输入命令中都运行这两个部分: java -jar Server-Chat-1.0.jarjava -jar Client-Chat-1.0.jar

Here is the output of server: 这是服务器的输出:

java.io.FileNotFoundException: config.properties (No such file or directory) at java.io.FileInputStream.open(Native Method) java.io.FileNotFoundException:java.io.FileInputStream.open(本机方法)处的config.properties(无此类文件或目录)

And client: 和客户:

eaProjects/Chat/target $ java -jar Client-Chat-1.0.jar java.io.FileNotFoundException: config.properties (No such file or directory) eaProjects / Chat / target $ java -jar Client-Chat-1.0.jar java.io.FileNotFoundException:config.properties(无此类文件或目录)

src/main/resources is maven convention to have resources file. src / main / resources是具有资源文件的常规约定。 When maven build jar/war artifact, it adds all files/directories from src/main/resources to classpath of resulting artifact . 当maven构建jar / war工件时,它将src / main / resources中的所有文件/目录添加到所得工件的classpath中

There is no src/main/resources available at runtime . 在运行时没有src / main / resources可用

In your case, you can update your program to read these files without giving any path. 在您的情况下,您可以更新程序以读取这些文件,而无需给出任何路径。 like below 像下面

private static final String RELATIVE_PATH_TO_PROPERTIES = "config.properties";
public static final String RELATIVE_LOG_PATH = "err_action.log";

The code below should allow to load the config.properties file located in resources folder which is deployed after the build to the root directory of the jar file: 下面的代码应允许加载位于resources文件夹中的config.properties文件,该文件在构建后部署到jar文件的根目录中:

public final class AppConfig {

private static final String RELATIVE_PATH_TO_PROPERTIES="config.properties";
...
private static Properties initProperties() {
    Properties properties = null;

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    FileInputStream input =    classLoader.getResourceAsStream(RELATIVE_PATH_TO_PROPERTIES);
    try {
        properties = new Properties();
        properties.load(input);
    } catch (IOException e) {
        e.printStackTrace();
    }
    ...
    return properties;
    }
}

IOW the following code allow to load a file from the class path of a jar app: IOW下面的代码允许从jar应用程序的类路径加载文件:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
FileInputStream input = classLoader.getResourceAsStream(<relative path of the file located in the jar app>);

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

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