我想阅读一些属性文件。 为此,我创建了一个小程序来读取、写入和更新此属性文件。
现在有些人说属性文件应该只读一次,这意味着当加载类时它应该读一次,而不是每个键多次。
所以我必须读取静态 block 中的属性文件。
现在我怀疑如果我在属性文件中添加任何新条目,它是否会加载新条目?
请建议我设计加载属性文件的正确方法。
public class Parser {
private String path;
private static Properties prop = new Properties();
public Parser(String path) throws IOException{
this.path = path;
load();
}
public Model readPropertiesFile(){
Model model = new Model();
model.setName(prop.getProperty("name"));
return model ;
}
public void createOrUpdatePropertiesFile(Model model){
prop.setProperty("name", model.getName());
}
public void setPath(String path){
this.path = path;
}
public String getPath(){
return path ;
}
public void load() throws IOException{
File file = new File(path);
if(!file.exists()){
file.createNewFile();
System.out.println("File created..");
}
prop.load(new FileInputStream(file));
}
最佳答案
你可以试试这个方法;
从类路径加载属性文件
public static Properties load(String propsName) throws Exception { Properties props = new Properties(); URL url = ClassLoader.getSystemResource(propsName); props.load(url.openStream()); return props; }
加载属性文件
public static Properties load(File propsFile) throws IOException { Properties props = new Properties(); FileInputStream fis = new FileInputStream(propsFile); props.load(fis); fis.close(); return props; }
关于java - 加载属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12294451/