无法在JAR中找到类路径资源(没有此类文件或目录)

时间:2017-10-30 06:56:39

标签: java maven intellij-idea resources classpath

我试图读取我在类路径中作为资源提供的文件

FileInputStream serviceAccount = new FileInputStream("firebase-service-account.json");

我已经尝试通过完整路径访问资源,绝对是一种流,而不是工作。

我的目标文件结构如下所示:

enter image description here

当我打开JAR时,我可以看到资源已正确捆绑,但我不确定它们是否正在流式传输。

enter image description here

如何访问我的资源?

Exception in thread "main" java.io.FileNotFoundException: java.io.BufferedInputStream@27d6c5e0 (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at com.lumos.xlsx_manager.es.da.Firebase.main(Firebase.java:146)

1 个答案:

答案 0 :(得分:0)

你可以尝试这样的事情,假设你只需要InputStream而不是特别FileInputStream

InputStream serviceAccount = null;
try{
    File f = new File("firebase-service-account.json");
    if (f.exists()){
        serviceAccount = new FileInputStream(f);
    } else {
        URL url = this.getClass().getResource("firebase-service-account.json");
        serviceAccount  = url.openConnection().getInputStream();
    }

    //Now do whatever you are doing with the InputStream...

    }catch (Exception e){
        e.printStackTrace();
    } finally{
        if (serviceAccount  != null) {
            try {
                serviceAccount .close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }