加载属性文件

时间:2014-09-08 09:08:51

标签: java properties filepath

我有像Code这样的东西,它工作正常,但如何 但我想用System.getProperty(“user.dir”)替换绝对路径; 但是这让我回到了一个带有反击的字符串我该如何解决它, 或者将其替换为将其转换为c:/ ........

public static void main(String[] args) throws Exception{

         String strPropertiePath=System.getProperty("user.dir");
         System.out.println("strPropertiePath "+strPropertiePath);


         String absoluthPath2Propertie = "C:/Users/maurice/Dropbox/a_projectturkey/solution_06_09_2014/Application_Propertie/logging.properties";

     File fileLog = new File(absoluthPath2Propertie);
     LogManager.getLogManager().readConfiguration(new FileInputStream(absoluthPath2Propertie));
     //ConfigSystem.setup();

}

}

3 个答案:

答案 0 :(得分:1)

只需使用具有正确父子关系的FilePath个对象即可。您无需关心斜杠和黑色斜杠,FilePath会为您照顾它们。

E.g。要定义属性文件,该文件位于props子文件夹中的用户目录文件夹中,文件名为myprops.properties,您可以像这样使用它:

File propFile = new File(System.getProperty("user.dir"),
    "/props/myprops.properties");

您可以像这样加载此属性文件:

// Use try-with-resources to properly close the file input stream
try (InputStream in = new FileInputStream(propFile)) {
    LogManager.getLogManager().readConfiguration(in);
}

修改

因此,如果您的用户目录中需要名为logging.properties的文件,只需使用:

File propFile = new File(System.getProperty("user.dir"),
    "logging.properties");
try (InputStream in = new FileInputStream(propFile)) {
    LogManager.getLogManager().readConfiguration(in);
}

答案 1 :(得分:1)

使用以下代码加载属性文件。

    Properties properties=new Properties();
    InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
    properties.load(in);

    properties.get("user.dir");

答案 2 :(得分:0)

您可以使用以下代码获取系统文件系统路径分隔符:

System.getProperties("file.separator")

通过使用此功能,您可以在任何支持的平台上创建正确的路径。这样就可以在基于UNIX / Linux的系统和Windows上的反斜杠中使用斜杠。