如何将 jar write/read 制作成外部文件

How to make jar write/read to external file

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

我的 jar 是通过 docker-compose 创建并在 /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 引导的情况下进行了快速测试,只是正常 Java 看看我的路径逻辑是否有误,但它运行良好。

任何见解将不胜感激

将您的路径更改为

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

那就试试吧。

由于您是从 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

现在主机 OS 上的 /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 个卷从主机 OS 读取文件。