简体   繁体   English

Jar 读取文件

[英]Jar that read file

I have a code that deals with elasticsearch index.我有一个处理 elasticsearch 索引的代码。 One of its steps, the program needs to read a jsonschema file in order to continue its execution.其中一个步骤是,程序需要读取 jsonschema 文件才能继续执行。 The code works well on my machine, but when I execute it as jar file inside a docker container, it gives me the following error:该代码在我的机器上运行良好,但是当我在 docker 容器内将其作为 jar 文件执行时,它给了我以下错误:

java.io.FileNotFoundException: dm.jsonschema (No such file or directory)

the code that loads the schema is:加载模式的代码是:

public class loadSchema {

private static final String JSON_SCHEMA_DOCUMENT = "dm.jsonschema";
....
public static JsonSchema tryLoadJSONSchema() {
    JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
    JsonNode cdmSchema = null;
    try {
        cdmSchema = JsonLoader.fromPath(JSON_SCHEMA_DOCUMENT);
    } catch (IOException e) {
        System.out.println(e);
        System.exit(-1);
    }

I placed the jsonschema file next to the jar file in the container, but it keeps giving me the same error.我将 jsonschema 文件放在容器中 jar 文件旁边,但它一直给我同样的错误。 Any idea how to solve this problem?知道如何解决这个问题吗?

The relative path of the File is resolved from wherever you are starting the java executable (mind the user.home ), not from where the jar archive was located.文件的相对路径是从您启动java可执行File的任何位置解析的(注意user.home ),而不是从 jar 存档所在的位置解析。

The best approach would be externalising this file location using a system property.最好的方法是使用系统属性将此文件位置外部化。 For example if you define a jsonSchemaPath property:例如,如果您定义jsonSchemaPath属性:

String path = Sytem.getProperty("jsonSchemaPath");
JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
JsonNode cdmSchema = JsonLoader.fromPath(path);

Then you can change it in the java command:然后您可以在 java 命令中更改它:

java -jar yourcode.jar -DjsonSchemaPath=/path/to/dm.jsonschema

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

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