【问题标题】:How can I read a java property file and get its values?如何读取 java 属性文件并获取其值?
【发布时间】:2013-01-31 19:17:22
【问题描述】:

在 Ruby 中,我有一个 sample.yml 文件,如下所示,

1_Group1:
   path:asdf
   filename:zxcv

2_Group2:
  path:qwer
  filename:poiu
etc etc............

现在我需要 Example.properties 文件 Java,其中应包含上述数据。

使用 Java,我想读取 Example.properties 文件。

然后需要根据组数对内容进行迭代,得到对应的“路径”和“文件名”值。

例如:如果有 5 个组.. Group1,Group2....Group5 然后我需要迭代

      for(int i=0; i< noofgroups(5);i++){
            ........................
           String slave =  aaa.getString("path");
            aaa.getString("filename");
        }

像这样我需要获取每个路径和文件名。

现在我有 Example.properties 如下,

   path:asdf
   filename:zxcv

它正在工作(我可以读取并获取值)

但我需要将可能的键作为“路径”和“文件名称”。所以我需要将它们分组。

【问题讨论】:

  • 我可以读取该文件并检索我现在需要的内容。但我需要有 3 或 4 个键作为“路径”和“文件名”。所以我提出了这个问题

标签: java properties


【解决方案1】:

如果要使用yaml格式,可以找yamlbeans

你可以这样使用它:

YamlReader reader = new YamlReader(new FileReader("sample.yml"));
Map map = (Map)reader.read();
System.out.println(map.get("1_Group1"));

【讨论】:

  • 谢谢。但是我们不能使用 sample.properties 来做到这一点?
  • @Prince 是的,你不能,因为sample.properties 使用java.util.Properties
  • 是的,我已经在使用 java.util.Properties。但我不知道如何在我的情况下使用它
【解决方案2】:

有很多方法可以解决这个问题;最自然的可能是使用自然分层的格式,例如 YAML、JSON 或 XML。

另一种选择是使用Commons Configuration hierarchical configs 技术之一,例如hierarchical INI style

如果您想使用“纯”属性文件,我建议您只需读取您的属性,将属性名称拆分为句点,然后存储到地图或类中,这样您就可以:

1_Group1.path=asdf
1_Group1.filename:zxcv

2_Group2.path=qwer
2_Group2.filename=poiu

【讨论】:

    【解决方案3】:

    您可以通过以下方式使用java.utils.Properties

    public static void loadPropertiesAndParse() {
        Properties props = new Properties();
        String propsFilename = "path_to_props_file";
        FileInputStream in = new FileInputStream(propsFilename);
        props.load(in);
        Enumeration en = props.keys();
        while (en.hasMoreElements()) {
            String tmpValue = (String) en.nextElement();
            String path = tmpValue.substring(0, tmpValue.lastIndexOf(File.separator)); // Get the path
            String filename = tmpValue.substring(tmpValue.lastIndexOf(File.separator) + 1, tmpValue.length()); // Get the filename
        }
    }
    

    您的properties 文件将如下所示:

    key_1=path_with_file_1
    key_2=path_with_file_2
    

    【讨论】:

      猜你喜欢
      • 2012-08-30
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2012-01-07
      • 1970-01-01
      • 2012-03-04
      相关资源
      最近更新 更多