我有一个写为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/

10-11 23:59
查看更多