将 InputStream 转换为 FileInputStream 不适用于 Apache POI
Converting InputStream to FileInputStream Not Working for Apache POI
我正在尝试从我的 res/raw 文件夹访问一个 excel 文件,我知道您只能使用 InputStream 来真正做到这一点;但是,Apache POI 中的 XSSFWorkbook 命令只采用 FileInputStreams 而不是 InputStreams:有没有办法做到这一点?我试过使用以下代码但出现此错误:java.lang.NullPointerException: Attempt to invoke virtual method 'java.net.URI java.net.URL.toURI()' on a null object reference
这是我试过使用的代码:
URL ins = this.getClass().getResource("ncaa.xlsx");
FileInputStream file = new FileInputStream(new File(ins.toURI()));
XSSFWorkbook workbook = new XSSFWorkbook(file);
is there any way to do this?
将原始资源复制到文件中,然后打开文件并将 FileInputStream
交给图书馆。
I've tried using the following
getResource()
与Android资源无关。要访问原始资源上的 InputStream
,请使用 getResources().openRawResource()
,在您的 Activity
或其他方便的 Context
.
上调用
作为 explained fairly clearly in the Apache POI documentation,如果您有文件,请不要使用 InputStream
!使用文件既更快又节省内存,因此应该比流更受欢迎,尤其是当您有一个文件开始时!
根据 Apache POI documentation on Files vs Streams,而不是您当前的代码:
URL ins = this.getClass().getResource("ncaa.xlsx");
FileInputStream file = new FileInputStream(new File(ins.toURI()));
XSSFWorkbook workbook = new XSSFWorkbook(file);
你应该改为:
URL ins = this.getClass().getResource("ncaa.xlsx");
if (ins == null)
throw new FileNotFoundException("The XLSX file didn't exist on the classpath");
File file = new new File(ins.toURI());
OPCPackage pkg = OPCPackage.open(file);
XSSFWorkbook workbook = new XSSFWorkbook(pkg);
您需要将 OPCPackage
保留到最后,这样您就可以关闭它以释放文件句柄资源
我正在尝试从我的 res/raw 文件夹访问一个 excel 文件,我知道您只能使用 InputStream 来真正做到这一点;但是,Apache POI 中的 XSSFWorkbook 命令只采用 FileInputStreams 而不是 InputStreams:有没有办法做到这一点?我试过使用以下代码但出现此错误:java.lang.NullPointerException: Attempt to invoke virtual method 'java.net.URI java.net.URL.toURI()' on a null object reference
这是我试过使用的代码:
URL ins = this.getClass().getResource("ncaa.xlsx");
FileInputStream file = new FileInputStream(new File(ins.toURI()));
XSSFWorkbook workbook = new XSSFWorkbook(file);
is there any way to do this?
将原始资源复制到文件中,然后打开文件并将 FileInputStream
交给图书馆。
I've tried using the following
getResource()
与Android资源无关。要访问原始资源上的 InputStream
,请使用 getResources().openRawResource()
,在您的 Activity
或其他方便的 Context
.
作为 explained fairly clearly in the Apache POI documentation,如果您有文件,请不要使用 InputStream
!使用文件既更快又节省内存,因此应该比流更受欢迎,尤其是当您有一个文件开始时!
根据 Apache POI documentation on Files vs Streams,而不是您当前的代码:
URL ins = this.getClass().getResource("ncaa.xlsx");
FileInputStream file = new FileInputStream(new File(ins.toURI()));
XSSFWorkbook workbook = new XSSFWorkbook(file);
你应该改为:
URL ins = this.getClass().getResource("ncaa.xlsx");
if (ins == null)
throw new FileNotFoundException("The XLSX file didn't exist on the classpath");
File file = new new File(ins.toURI());
OPCPackage pkg = OPCPackage.open(file);
XSSFWorkbook workbook = new XSSFWorkbook(pkg);
您需要将 OPCPackage
保留到最后,这样您就可以关闭它以释放文件句柄资源