【问题标题】:Load a Propertie File加载属性文件
【发布时间】:2014-09-08 09:08:51
【问题描述】:

我有类似这样的代码,它工作正常,但如何 但我想用 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();

}

}

【问题讨论】:

    标签: java properties filepath


    【解决方案1】:

    只需使用具有适当父子关系的FilePath 对象。你不需要关心斜线和黑斜线,FilePath 会为你处理它们。

    例如要定义一个属性文件,该文件位于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);
    }
    

    【讨论】:

    • user.dir 还给我:C:\Users\maurice\Dropbox\a_projectturkey\solution_06_09_2014\Application_Propert‌​ie
    • 但我需要以下路径:C:/Users/maurice/Dropbox/a_projectturkey/solution_06_09_2014/Application_Propert‌​ie/logging.properties"
    • 解决方案可能很简单,但我不知道我该怎么做,准备 user.dir 的字符串以便我得到:c:/..../..../ -
    • 已编辑,添加了您的具体案例。你不需要关心斜线和黑斜线,File 会为你处理。
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      System.getProperties("file.separator")
      

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

      【讨论】:

      • user.dir 还给我:C:\Users\maurice\Dropbox\a_projectturkey\solution_06_09_2014\Application_Propertie
      • 但我需要以下路径:C:/Users/maurice/Dropbox/a_projectturkey/solution_06_09_2014/Application_Propertie/logging.properties"
      • 解决方案是可能的,简单但我不知道我该怎么做,准备 user.dir 的字符串以便我得到:c:/..../..../跨度>
      猜你喜欢
      • 2013-01-15
      • 2015-12-15
      • 1970-01-01
      • 2012-04-28
      • 2011-06-20
      • 2011-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多