我有一个读取方法,它从文本文件中获取键和值,例如,如果我有:
Name: <name>
它会得到值
唯一要考虑的是使用属性,但我真的不知道如何将它们应用于路径示例:
Students:
Name: <Name>
我希望得到类似这样的内容read("students.name");
输出将是名称
到目前为止我做了什么
public String read () {
Properties properties = new Properties();
try {
properties.load(new FileInputStream(file.getPath()));
for(String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
return value;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@TimBiegeleisen这是我现在尝试过的,也许你可以帮助我吗?
答案 0 :(得分:0)
要使用属性文件,您的数据必须采用正确的格式。对于上面的示例,您需要使用属性文件:
students.name=Ed
如果您想使用您列出的格式,即
Students:
Name: Ed
然后你需要编写自己的解析机制来提取数据。
我刚看到你在“学生”下有多个名字的评论。这使得属性文件无用,如果您打算一次读取所有名称,您的代码本身就需要返回一个ArrayList。
答案 1 :(得分:0)
如果继续使用Properties
,则需要略微更改format of your file:
students.name1 = <name1>
students.name2 = <name2>
我个人会将Properties
对象分配给static
变量,以便每次调用read
时加载相同的文件,以便您的方法成为:
public String read (String key) {
if(properties == null){
Properties prop = new Properties();
try {
prop.load(new FileInputStream(file.getPath()));
properties = prop;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
if(properties != null){
return properties.get(key);
}
return null;
}
这样,如果你拨打read("students.name1")
,就会得到第一个学生的名字。