【问题标题】:FileInputStream fails on properties fileFileInputStream 在属性文件上失败
【发布时间】:2016-03-07 13:57:37
【问题描述】:

PROJECT/resources/properties.properties 中的此属性文件可以通过以下方式读取并显示其内容:

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 处出现空指针异常并使用该代码失败

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)

任何人都知道为什么这两种方法的属性文本文件的路径相同?

【问题讨论】:

    标签: java


    【解决方案1】:

    由于第一个代码 sn-p 有效,似乎 properties 被作为 null 传递给 getProperties() 方法,导致 NullPointerException

    理想情况下,我们根本不应该传递properties。我们只需要创建一个新的object 并返回它。

    【讨论】:

    • 其实你是对的。我只是不明白为什么我不能用新属性扩展属性,以为这是一个无穷无尽的哈希表!?实际上想在 web.properties、db 属性等文件中分离属性。
    • 我们不需要扩展属性。我们可以在任何现有的属性对象上调用putAll 方法来添加新属性(另一个对象)。例如。 Properties p = new Properties(); p.putAll(p1);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 2016-07-15
    • 1970-01-01
    • 2016-05-21
    • 2012-07-08
    • 1970-01-01
    相关资源
    最近更新 更多