我有一个作为 Spark Streaming 作业编写的 Java 应用程序,它需要一些文本资源,我已将这些资源包含在资源目录中的 jar 中(使用默认的 Maven 目录结构)。通过单元测试,我可以毫无问题地访问这些文件,但是当我使用 spark-submit 运行我的程序时,我得到一个 FileNotFoundException。使用 spark-submit 运行时,如何访问我的 JAR 中类路径中的文件?
我目前用来访问我的文件的代码大致如下所示:
InputStream input;
try {
URL url = this.getClass().getClassLoader().getResource("my file");
if (url == null) {
throw new IOException("file does not exist");
}
String path = url.getPath();
input = new FileInputStream(path);
} catch(IOException e) {
throw new RuntimeException(e);
}
谢谢。
请注意,这不是 Reading a resource file from within jar 的副本(建议),因为此代码在本地运行时有效。它仅在 Spark 集群中运行时失败。
最佳答案
我通过一种不同的(并且明显不那么愚蠢)的方式访问资源目录来解决这个问题:
input = MyClass.class.getResourceAsStream("/my file");
关于java - 从 Apache Spark Streaming 上下文访问 JAR 资源目录中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40252652/