Java InputStream无法从JAR中读取文件 [英] Java InputStream fails to read file from within JAR

查看:222
本文介绍了Java InputStream无法从JAR中读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我的可执行文件.jar文件中读取一个文件,但它一直在获取空值。

I am trying to read a file from my executable .jar file but it keeps getting null values.

我有这段代码:

public DanceEventTicketScanner(String txtfile){
    sv = new ScannerView(this);
    findcode = false;
    InputStream is = this.getClass().getResourceAsStream("/resources/copy.csv");
    if (is == null) JOptionPane.showMessageDialog(null, "Resource not located.");
}

在JAR文件中,我(正常情况下)包含所有我的文件夹。类文件,并在同一目录中包含一个名为resources的文件夹,其中包含copy.csv文件。

In the JAR file i have (as normal) a folder containing all my .class files and in the same directory a folder named resources which holds the copy.csv file.

但此代码无法识别该文件。

This code however does not recognize the file.

有没有人有任何想法?

推荐答案

getClass()。getResourceAsStream(..)将使用相对于类的路径(所以inc。包dirs)。 getClass()。getClassLoader()。getResourceAsStream(..)将使用绝对路径。因此,更改代码并获取类加载器,它将起作用。

getClass().getResourceAsStream(..) will use a path relative to the class (so inc. package dirs). getClass().getClassLoader().getResourceAsStream(..) will use an absolute path. So change your code and get the class loader and it will work.

这篇关于Java InputStream无法从JAR中读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆