2012-09-06 127 views
2

我想读取一些属性文件。 为此,我创建了一个读取,写入并更新此属性文件的小程序。加载属性文件

现在有些人说属性文件只能被读取一次,这意味着当类被加载时,它应该只读一次,而不是每个键的多次。

所以我必须读取静态块内的属性文件。

现在我怀疑如果我做任何新的条目属性文件,它会被加载新条目?

请建议我哪个是设计加载属性文件的正确方法。

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)); 





    } 
+0

属性文件应在运行时(动态)。可你看你的代码加载你试过了什么? – Ami

+0

当然。我将添加代码。 – user414967

+1

为了更快提供更好的帮助,请发布[SSCCE](http://sscce.org/)(与代码片段或400行相对)。 –

回答

0

你可以试试这个方法;

  • 负载特性从类路径文件

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