java - 读取外部属性文件 Java/Linux

标签 java linux jar properties

我的任务是编写一些代码,根据我所处的环境(生产或测试)提取属性文件。所以 jar 文件在每个环境中都是相同的,但是一些变量会根据 jar 执行的环境而改变。导演看起来像这样:

[ProgramOne.jar ProgramTwo.jar ProgramThree.jar mypropertiesfile.properties]

我需要这些 jar 中的每一个来读取属性文件。我正在阅读这样的内容:

   try(InputStream theResourceStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("mypropertiesfile.properties"))

我还没有访问这些环境的权限,并且将有一个非常小的窗口来实现此代码。我的问题是,根据我的情况,这是读取属性文件的正确方法吗?这会起作用吗?我试过在我的本地机器上加载文件,但一切都返回 null。

最佳答案

如果它不能在您的机器上运行,那么它可能无法在其他机器上运行。

当我认为您想从同一目录中的外部文件加载属性时,您似乎正在尝试从 Jar 加载资源。

试试这个:
test.properties 在与 Jar 相同的目录中,具有属性 my-property=this is a test

public class Main {
    public static void main(String[] args){ new Main().test(); }

    /** Usually gets the `JAR` directory or the `bin` when running in IDE */
    public String getCodeSourcePath() throws SecurityException, URISyntaxException {
        return getClass().getProtectionDomain().getCodeSource().getLocation()
            .toURI().getPath();
    }

    public void test() {
        // TODO handle exceptions, unlikely to occur unless you do something weird
        String jarPath = getCodeSourcePath();

        Properties properties = new Properties();
        File file = new File(jarPath, "test.properties");
        try (FileInputStream fis = new FileInputStream(file);) {
            properties.load(fis);
        }
        System.out.println(properties.getProperty("my-property"));

    }
}

输出:这是一个测试

关于java - 读取外部属性文件 Java/Linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51272703/

相关文章:

java - 在方法中的循环外部提取变量

java - StdAudio 类使我的 JFrame 不显示

linux - 在 U-boot 期间或 U-boot 之后立即启动 spidev 程序

java - 通过命令提示符修改现有的 jar 文件

java - 如何在没有 native 安装程序的情况下为使用 JavaFX 的应用程序制作可运行的 jar

java - JDK/JRE 安装程序无法在 x64 上运行

java - Spring 没有 Autowiring 我的过滤器类

C : String comparing

linux - 保持 *nix 格式

java - Hadoop FileAlreadyExistsException : Output directory hdfs://<namenode public dns>:9000/input already exists