有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我在使用InputStream和类加载器函数时遇到空指针异常,但在使用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;
}

共 (1) 个答案

  1. # 1 楼答案

    在您的案例中,getResourceAsStream-方法将在类的包中进行搜索

    ClassLoad.getResource

    This method will first search the parent class loader for the resource; if the parent is null the path of the class loader built-in to the virtual machine is searched. That failing, this method will invoke findResource(String) to find the resource.

    这些ClassLoader方法用于搜索可能捆绑的java应用程序(例如,作为jar文件),而不是搜索应用程序旁边的文件,这似乎是您在本例中想要做的事情。见ClassLoader JavaDoc

    如果ClassLoader无法找到资源,getResource*-方法将返回null,因此代码将失败(NullPointerException->;流为null

    更新:如果属性文件位于项目的根目录中,则在使用类加载器时,可以在路径开头使用/来尝试。详见this thread