【问题标题】:How to make jar write/read to external file如何使 jar 写入/读取到外部文件
【发布时间】:2020-10-17 16:07:57
【问题描述】:

我的 jar 用于读取和写入 .json 文件。为此,我决定使用一个外部文件来读取和写入。

我的 jar 是通过 docker-compose up 创建的,并在 /a/b/c/d/app.jar 中运行

我要与之交互的 .json 文件在 /homeDir/Documents/file.json 中

JSONObject aJQLs = new JSONObject(IOUtils.toString(new FileInputStream("/Documents/file.json"), "UTF-8")); 

但是,我不断收到 FileNotFoundException。

我认为这就像输入文件的绝对路径一样简单。

我收到以下错误日志

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 
'jiraAutomationController' defined in URL [jar:file:/app.jar!/BOOT-
INF/classes!/com/company/jiraautomation/controller/JiraAutomationController.class]: Instantiation of bean 
failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate 
[com.company.jiraautomation.controller.JiraAutomationController]: Constructor threw exception; nested 
exception is java.io.FileNotFoundException: /Documents/file.json (No such file or directory)

jar 是否可以按照我想要的方式与外部文件交互?

运行jar时我对文件路径的理解有问题吗?

我在没有 Spring Boot 的情况下进行了快速测试,只是使用普通 Java 来查看我的路径逻辑是否有问题,但它运行良好。

任何见解将不胜感激

【问题讨论】:

  • 你能分享你如何访问这个automation_jql.json
  • automation_jql.json 与 file.json 相同。抱歉,我会修改它。

标签: java spring spring-boot jar path


【解决方案1】:

由于您是从 docker 容器内运行 jar,因此 docker 容器与主机操作系统隔离运行,因此无法访问主机系统上的任何文件。

但是,您可以将卷从主机系统安装到您的 docker 容器。

Docker 主机安装卷

语法:/host/path:/container/path

主机路径可以定义为绝对路径或相对路径。

例子:

version: '3'
services:
  app:
    image: nginx:alpine
    ports:
      - 80:80
    volumes:
      - /var/opt/my_website/dist:/usr/share/nginx/html

在您的情况下,您可以将以下内容添加到您的 docker-compose.yml 到相关服务中 -

volumes:
  - /homeDir/Documents:/user/local/Documents

现在您在主机操作系统上的 /homeDir/Documents 将被挂载到容器上的 /user/local/Documents/user/local/Documents 这个目录将由 docker 自动创建)。在此之后修改您的 java 代码以从容器内的位置读取文件,即/user/local/Documents/file.json(如卷中定义),如下所示 -

JSONObject object = new JSONObject(IOUtils.toString(new FileInputStream("/user/local/Documents/file.json"), "UTF-8")); 

现在您的程序应该能够使用 docker 卷从主机操作系统读取文件了。

【讨论】:

    【解决方案2】:

    改变你的路径

    "file:///Documents/file.json"
    

    那就试试吧。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-09
      • 2012-12-25
      • 2013-12-08
      • 2012-10-28
      • 2013-04-12
      • 2015-12-23
      • 2016-08-30
      相关资源
      最近更新 更多