Gnik
Gnik

Reputation: 7426

How can I read a java property file and get its values?

In Ruby I have a sample.yml file as below,

1_Group1:
   path:asdf
   filename:zxcv

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

Now I need to have Example.properties file Java, which should contains data as above.

Using Java, I want to read the Example.properties file.

Then need to iterate the contents based on the number of groups and get the corresponding "path" and "filename" values.

For eg: If there are 5 groups.. Group1,Group2....Group5 Then I need to iterate

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

Like this I need to get each path and filename.

Now I have Example.properties as follws,

   path:asdf
   filename:zxcv

It is working (I can read and get the values)

But I need to have may keys as "path" and " fileneame". SO I need to group them.

Upvotes: 0

Views: 4312

Answers (3)

Michael
Michael

Reputation: 1237

You can use java.utils.Properties in the following way:

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
    }
}

And your properties file will look like this:

key_1=path_with_file_1
key_2=path_with_file_2

Upvotes: 1

Dave Newton
Dave Newton

Reputation: 160170

There are a number of ways to go about this; the most natural might be to use a naturally-hierarchical format, like YAML, JSON, or XML.

Another option is to use one of the Commons Configuration hierarchical configs techniques like a hierarchical INI style.

If you want to use a "pure" property file I'd suggest just reading in your properties, splitting the property names on periods, and storing to a map or class, so you'd have:

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

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

Upvotes: 1

isvforall
isvforall

Reputation: 8926

If you want to use yaml format, you can find out a yamlbeans

You can using it like this:

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

Upvotes: 1

Related Questions