首页 > 解决方案 > 如何迭代位于运行的 .jar 文件之外的文件夹

问题描述

我的 java 应用程序架构有问题。我想提供一个使用 Spring Boot 生成的简单 .jar 文件。在运行 .jar 之后,我需要遍历另一个文件夹中的文件。这是我的目录的层次结构:

在此处输入图像描述

  1. 我使用 .bat 或 sh 启动我的 .jar,使用 java -jar myApp.jar
  2. 我必须迭代 myApp/files 中存在的所有文件

看起来很简单,但我找不到办法做到这一点!我尝试了很多在这里找到的东西,但没有任何效果!

我试试这个,但有一个 nullPointer ......

File jarFile = new File(myMainClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());
        String jarLocation = jarFile.getPath();

你能帮我做一些尝试吗!

谢谢 !

标签: javaspring-bootfilejar

解决方案


编辑您的 .bat 文件以像这样开始进入您的 myApp 文件夹

@echo off

#do stuff

cd %myApp_folder%

java -jar myapp.jar

你可以通过这样的相对路径解析你的文件夹:

File confFolder = new File("conf");
File filesFolder = new File("files");

推荐阅读