如何在linux os中使用java从特定位置读取.properties文件

时间:2015-08-06 05:04:17

标签: java linux windows properties-file

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

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

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

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

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

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

也产生了FileNotFoundException。有人可以帮我吗?感谢。

2 个答案:

答案 0 :(得分:0)

如果文件不存在,FileOutputStream将创建该文件,但如果该目录不存在,将不会创建任何目录部分,并且会因FileNotFoundException 而失败。在编写之前,您应该检查目录是否存在。

还要在unix中检查该目录的写权限。

答案 1 :(得分:0)

这样做:

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。我希望这对你有帮助!