使用输入Stream读取java属性文件

时间:2014-11-17 07:11:31

标签: java

我在使用InputStream和类Loader函数时遇到空指针异常,但在使用FileInputStream时它正在正确读取属性文件。

为什么我收到此错误?以下是我的代码。

public String readProperties()
{

    String result = "";
    Properties prop = new Properties();
    String file = "test.properties";
    //InputStream fins = getClass().getClassLoader().getResourceAsStream(file); 
    try 
    {
        prop.load(new FileInputStream(file));
        //prop.load(fins);
    } 
    catch (IOException e) {
        e.printStackTrace();
    }

    String nation = prop.getProperty("Nation");
    String city = prop.getProperty("City");
    String state = prop.getProperty("State");
    result = "I live in "+city+" in "+state+" in "+nation;
    return result;
}

3 个答案:

答案 0 :(得分:5)

确保将test.properties文件保存在类路径中:即在应用程序的Src文件夹中

这是示例代码:

package com.example;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ReadProperties {

    public static void main(String[] args) {        

        ReadProperties r = new ReadProperties();        
        String  result = r.readProperties();
        System.out.println("Result   : " + result);
    }

    public String readProperties()
    {
        String result = "";
        Properties prop = new Properties();
        String file = "test.properties";
        InputStream fins = getClass().getClassLoader().getResourceAsStream(file); 
        try 
        {
            //prop.load(new FileInputStream(file));
            if(fins!=null)
                prop.load(fins);        
        } 
        catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }

        String nation = prop.getProperty("Nation");
        String city = prop.getProperty("City");
        String state = prop.getProperty("State");
        result = "I live in "+city+" in "+state+" in "+nation;
        return result;
    }

}

答案 1 :(得分:2)

getResourceAsStream - 方法将在您的案例中搜索您的课程包。

来自ClassLoad.getResource

  

此方法将首先在父类加载器中搜索资源;如果父项为null,则搜索内置到虚拟机的类加载器的路径。如果失败,此方法将调用findResource(String)来查找资源。

这些ClassLoader - 方法用于搜索可能捆绑的Java应用程序(例如,作为jar文件),而不是用于搜索应用程序旁边的文件,这看起来就像你想要做的那样。请参阅ClassLoader JavaDoc

如果ClassLoader无法找到资源,则getResource* - 方法将返回null,因此您的代码将失败(NullPointerException - >该流是null)。

更新:如果属性文件位于项目的根目录中,则可以在使用ClassLoader时在路径开头使用/进行尝试。有关详细信息,请参阅this thread

答案 2 :(得分:0)

代码可能是这样的:

String file = "/test.properties";
InputStream fins = getClass().getResourceAsStream(file); 
InputStream fins = MyClass.class.getResourceAsStream(file); 

相对于getClass()的类,寻找资源,但是使用起始/使其成为绝对资源。但是,使用getClass()意味着实际的类可能来自另一个jar,因此使用实际的类名可能更好。

与使用File相比,资源可能来自jar(zip格式)。由于Windows上的文件不区分大小写,因此可能使用File在Windows上运行Test.properties,而不是作为资源或其他平台(Linux,MacOSX)。

打开jar(zip)并检查test.properties是否存在。

为了完整起见:您还可以使用ClassLoader来获取资源。这是很好的jar。然而,路径必须是绝对的,而不是从/开始。

相关问题