Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用java读取文件时出现NullpointerException_Java_File - Fatal编程技术网

使用java读取文件时出现NullpointerException

使用java读取文件时出现NullpointerException,java,file,Java,File,我有一个构造函数,上面提到要读取xls文件,以便被jxcelapi操作 Fill(String file, int sheet, int cols, int rows) { vService = new VipServiceImpl(); java.net.URL url = this.getClass().getResource("vips.xls"); System.out.println(url); //This gave me null Fi

我有一个构造函数,上面提到要读取
xls
文件,以便被jxcelapi操作

Fill(String file, int sheet, int cols, int rows) {
    vService = new VipServiceImpl();        
    java.net.URL url = this.getClass().getResource("vips.xls");

System.out.println(url);  //This gave me  null
    File f;
    try {
        f = new File(url.toURI());
    } catch (URISyntaxException e) {
        f = new File(url.getPath());
    }
    excelHandler = new ExcelHandler(f, sheet, cols, rows);
}
我必须提到,我已将文件
vips.xls
放在
Fill
类文件相同的目录中,但它在
新文件(url.toURI())的行上给了我一个空指针异常

更新:
我现在真的做了类路径和文件系统路径之间的区别:(

添加一个前导斜杠来表示类路径的根

this.getClass().getResource("/vips.xls");

在一个新的Eclipse项目中,您提供的示例确实适用于我,因此这使我相信您存在环境问题。我能想到的最可能的情况是,当应用程序打包在jar中时,您正在执行该应用程序。这将是一个问题的原因如下:

类路径中的URI并不总是与系统上的文件路径相同。您不应使用:

new File(getClass().getResource("vips.xls"))

请参见

简单地说,在将文件复制到目录中后,我应该对我的eclipse项目进行
刷新,

仔细检查文件名。将文件临时加载到另一个位置,并尝试从另一个位置加载它(例如C://)-错误是否仍然存在?
System.out.println(url);
给了我
null
“在同一文件夹中"“文件夹”是指目录的图形用户界面的概念。如果您指的是目录,请键入。但此资源是否随应用程序一起提供。?在部署时,这些资源可能会成为。在这种情况下,必须通过
URL
而不是
文件
访问资源。请参阅标签,以获取形成
URL
@HoussemBdr的方法。您应该发布关于如何执行程序的详细说明,例如:它是否打包在JAR中?您是否使用Maven?从我的回答中注意,我的示例运行良好,因此您遇到了某种环境问题。OP说该文件位于同一个fo中这是错误的。我的意思是在与类文件相同的文件夹中,更正:)完全正确。这是一个环境问题。如果您向我们提供了从Eclipse运行的信息,我们可能会建议刷新/清理/编译您的项目。我建议你在以后的问题中提供更多类似的信息:)@torbinsky你完全正确,下次我会努力提高效率:)