首页 > 解决方案 > 将外部文件夹添加到可运行 jar 中的 ClassPath

问题描述

我有一个 maven 项目,我使用 maven 程序集插件创建了一个带有依赖项的 jar。我还有一个外部配置文件( conf.properties ),jar 需要它才能正常工作。

我的项目结构是这样的:

  |- abc.jar
  |- config
     |-conf.properties

如何将此配置文件夹添加到 jar 文件的类路径中?我尝试使用-cp命令并在文件中操作类路径属性来做到这一点,MANIFEST.MF但到目前为止还没有运气。

有谁知道这样做的方法?

标签: javamaven

解决方案


This is how I tested (sorry, no maven)!

Main class:

package cfh.sf.Chamika;

import java.util.ResourceBundle;

public class ABC {

    public static void main(String[] args) {
        var bundle = ResourceBundle.getBundle("conf");
        System.out.println(bundle.getString("test"));
    }
}

Manifest file, note empty line at end (entries must end with a newline (CR, LF or CRLF)):

Manifest-Version: 1.0
Main-Class: cfh.sf.Chamika.ABC
Class-Path: config/

Directory structure

dist/
    abc.jar
    config/
        conf.properties

Content of conf.properties:

test = OK, it is working!

Executed with

java -jar abc.jar

Alternative, not using ResourceBundle:

package cfh.sf.Chamika;

import java.io.IOException;

public class ABC {

    public static void main(String[] args) {
        try (var input = ClassLoader.getSystemResourceAsStream("conf.properties")) {
            int ch;
            while ((ch = input.read()) != -1) {
                System.out.print((char) ch);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

推荐阅读