如何高效读取元数据文件?

发布于 2024-10-07 08:43:52 字数 522 浏览 2 评论 0原文

我当前的项目正在使用元数据文件来设置属性,而无需编译。目前我以这种方式设置:

metadata.txt
[property] value <br/>
[property2] value2

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

现在使用 BufferedReader 读取此文件并按特定顺序获取信息。如:

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

我想知道是否有更好的方法可以做到这一点而不必逐行阅读?我试图考虑使用循环,但我不确定这会如何解决,因为我想为每个属性设置不同的字符串变量。

另外,我在这个程序中没有使用 GUI,所以这就是我编辑原始数据的原因。

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

多像笑话 2024-10-14 08:43:52

而是使用 java.util.PropertiesAPI。它正是为此目的而设计的。

创建一个 filename.properties 文件,其中 key=value 条目以换行符分隔:

key1=value1
key2=value2
key3=value3

将文件放入类路径中(或将其路径添加到类路径中)并加载它,如下所示:

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

然后您可以通过键获取值如下:

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

另请参阅:

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:

╰つ倒转 2024-10-14 08:43:52

我不确定这是这个问题的答案。

您可以使用 java.util.Properties 及其方法来保存或加载文件中的属性。如果您不打算做一些特殊的事情,那么您的元数据文件看起来就像一个属性文件。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文