尝试读取Excel文件时出错

时间:2014-08-22 05:46:20

标签: java

当我运行以下代码时:

Properties p = new Properties();
public Properties getObjectRepository() throws IOException{
 //Read object repository file
InputStream stream = new FileInputStream(new File(System.getProperty("D:\\src\\objects\\object.properties")));
     //load all objects
p.load(stream);
return p;
}

它显示错误:

Exception in thread "main" java.lang.NullPointerException
    at java.io.File.<init>(Unknown Source)
    at uioperation.Excel_object.getObjectRepository(Excel_object.java:14)
    at ExecuteTestcase.Testcase_execute.main(Testcase_execute.java:27)

我的代码出了什么问题?

2 个答案:

答案 0 :(得分:2)

我不相信你有一个名为D:\\src\\objects\\object.properties

的系统属性

所以

更改为

new File("D:\\src\\objects\\object.properties"));

假设此文件存在

答案 1 :(得分:0)

似乎您的代码没有实现设置属性,但您只需使用以下代码打开文件。

Properties p = new Properties();
public Properties getObjectRepository() throws IOException{
    //Read object repository file

    String FileName="Path to your file"; 
    InputStream stream = new FileInputStream(new File(fileName));
    //load all objects
    p.load(stream);
    return p;
}

否则,您应该从系统属性中获取它。

    Properties p = new Properties();
public Properties getObjectRepository() throws IOException{
    //Read object repository file

    String FileName=System.getProperty("Prperty Key for your file path"); // the property should ave been already set somewhere in the code before execution of this line
    InputStream stream = new FileInputStream(new File(fileName));
    //load all objects
    p.load(stream);
    return p;
}

这是用于设置属性和访问文件

Properties p = new Properties();
public Properties getObjectRepository() throws IOException{

    //Set Property for file path

    setProperty("filePath","D:\\src\\objects\\object.properties");
    //Read object repository file

   String FileName=System.getProperty("filePath"); //now fileName is similar to "D:\\src\\objects\\object.properties"
    InputStream stream = new FileInputStream(new File(fileName));
    //load all objects
    p.load(stream);
    return p;
}