从资源文件夹读取文件时出现空指针异常

Getting nullpointerexception while reading file from resource folder

当我尝试读取位于 src/main/resources 位置的文件时,我得到了 NullpointerException。当我以 jar 格式 运行 时发生。但是当我编译代码并 运行 它时,它 运行 在 Intellij 中很好。

注意:我正在使用 sbt 包来构建 jar 并 运行ning 它。

请帮忙。谢谢!

无法再从文件系统访问已打包到 JAR 中的文件。这可以在查看从 myClass.getResource("file.txt") 返回的 URL 时看到,例如:

/home/sria/cde-spark-assembly-1.0.jar!/file.txt

注意 ! 表示该文件已打包到 JAR 中。


这意味着您始终必须使用以下模式访问资源文件:

对于 src/main/resources/file.txt 中的文件:

myClass.getResourceAsStream("file.txt")

您可能不想这样做的原因有两个:

  1. 将文件添加到资源目录会增加 JAR 文件的大小。
  2. 无法使用标准文件系统操作访问该文件。

作为替代方案,您可以从文件系统中的(可配置的)路径加载文件,例如:

val inputStream = new BufferedInputStream(new FileInputStream(myPath))

(reference)

您可以通过这种方式加载文件,例如相对于 JAR file path or the execution directory.


希望对您有所帮助。

注意:sbt packagesbt assembly都会将资源文件打包到JAR中。