2016-03-07 93 views
1

这种特性在PROJECT/ressources文件/ properties.properties可以读取并显示它的内容与的FileInputStream失败的属性文件

public void showFileContent(String fileName){ 

    File file = new File (fileName); 
    FileInputStream input = null; 

    if(file.exists()){ 
     int content; 
     try { 
      input = new FileInputStream(fileName); 
      while ((content = input.read()) != -1) { 
       System.out.print((char) content); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     }finally { 
      if (input != null) { 
       try { 
        input.close(); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     }  
    }else{ 
     System.out.println("Error : properties File " + fileName + " not found"); 
    } 
} 

但在properties.load一个空指针异常failes与代码

public Properties getProperties(String fileName, Properties properties){ 

    File file = new File (fileName); 
    InputStream input = null; 

    if(file.exists()){ 
     try { 
      input = new FileInputStream(fileName); 
      properties.load(input); 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } finally { 
      if (input != null) { 
       try { 
        input.close(); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    }else{ 
     System.out.println("Error : properties File " + fileName + " not found"); 
    } 
    return properties; 
} 

即使输入设置为

input = this.getClass().getClassLoader().getResourceAsStream(fileName) 

的人都知道为什么,可以是FO在两个方法的相同路径中使用属性文本文件?

回答

3

由于第一个代码段工作,看起来properties作为空传递给getProperties()方法,导致NullPointerException

理想情况下,我们不应该通过properties。我们只需要创建一个新的object并将其返回。

+0

其实你是对的。我只是不明白为什么我不能用新的属性扩展属性,认为它是一个无尽的哈希表! 实际上想要像web.properties,db属性等文件中的属性。 – user3732793

+0

我们不需要扩展属性。我们可以在任何现有的属性对象上调用'putAll'方法来添加新的属性(另一个对象)。例如。 'Properties p = new Properties(); p.putAll(p1);' –

+0

谢谢你! – user3732793