开发者

How to read a metadata file efficiently?

My current project is using a metadata file to set properties without having to compile. Currently I have it set up in this way:

metadata开发者_JAVA技巧.txt
[property] value <br/>
[property2] value2

File f = new File("metadata.txt");
BufferedReader in = new BufferedReader(new FileReader(f));
String variable1 = "";
String variable2 = "";

Now read this file using a BufferedReader and getting the information in a certain order. Such as:

variable1 = in.readLine();
variable2 = in.readLine();

I was wondering is there a better way to do this without having to read line by line? I was trying to think of using a loop but I'm not sure how that would work out since I want to set different String variables to each property.

Also I'm not using a GUI in this program so that is the reason why I'm editing the data raw.


Rather use the java.util.Properties API. It's designed exactly for this purpose.

Create a filename.properties file with key=value entries separated by newlines:

key1=value1
key2=value2
key3=value3

Put the file in the classpath (or add its path to the classpath) and load it as follows:

Properties properties = new Properties();
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("filename.properties"));

Then you can obtain values by key as follows:

String key1 = properties.getProperty("key1"); // returns value1

See also:

  • Properties tutorial


I'm not sure this is an answer to this question.

You can use java.util.Properties and its methods to save or load properties from the file. You metadata file looks like a property file, if you don't target doing something special.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜