【问题标题】:how to read .properties file from particular location using java in linux os如何在 linux os 中使用 java 从特定位置读取 .properties 文件
【发布时间】:2015-08-06 05:04:16
【问题描述】:

大家好,我在以下文件夹结构中有 2 个 jar 文件(read.jar、write.jar):

app/read/read.jar
app/write/write.jar

write.jar 将值写入app/important.properties 中的属性文件,read.jarapp/important.properties 中读取。在 Java 代码中,我使用

调用属性文件
FileOutputStream out = new FileOutputStream("/app/important.properties");

这在 Windows 操作系统中运行良好,但是当我将这个 app 放入 Linux 操作系统中时,/home/workspace/app 会抛出 FileNotFoundException。然后我将文件的读取更改为:

FileOutputStream out = new FileOutputStream("./important.properties")

这也产生了FileNotFoundException。任何人都可以帮助我吗?谢谢。

【问题讨论】:

  • 确保您使用的是相对路径,因为您的第一个路径是来自根/app 目录的绝对路径
  • 你是在读写important.properties还是height.properties??
  • 对不起,我正在阅读重要的.properties 如何在 linux 中给出路径?它总是说找不到文件异常
  • 您是否尝试过简单地使用"important.properties""/home/workspace/app/important.properties"
  • 在 Windows 中它工作正常,我给了这样的/app/important.properties 但在 linux 中它不工作。

标签: java linux windows properties-file


【解决方案1】:

如果文件不存在,FileOutputStream 将创建该文件,但如果该目录不存在,它不会创建任何目录部分并失败并返回 FileNotFoundException。你应该在写之前检查目录是否存在。

同时在 unix 中检查该目录的写权限。

【讨论】:

    【解决方案2】:

    这样做:

    public static void loadProperFile(String fileName){
        try {
            String url=ReadProperties.class.getResource("/").toURI().getPath();
            String path=url+fileName;
            properties.load(new FileInputStream(path));
    
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
    

    它适用于mac和linux。我希望这对你有帮助!

    【讨论】:

    • 或者您可以使用系统属性“user.dir”或 File(".") 这将返回当前工作目录(恕我直言,更容易阅读:P)
    • 它正在/app/write 文件夹中创建属性文件。但我需要在/app 文件夹中创建属性文件。
    • 如果属性文件在 .jar 中,我建议使用上面的代码 getResourceStream()。不过干得好。
    猜你喜欢
    • 2020-04-14
    • 2017-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    相关资源
    最近更新 更多