下载一个zip,解压缩并解析它 - 全部在内存中 - Java

问题描述 投票:0回答:2

我有一个包含.CSV文件的.zip文件的URL。

我正在编写一个Java应用程序,需要下载.zip文件并访问.zip中的CSV文件,并使用Apache Commons CSV在CSVRecords列表中解析它们。我不想将任何文件写入磁盘,因为这是一种性能浪费。

这是我到目前为止(我现在省略了所有错误处理,它只是一个POC):

URL url = new URL(myURLString);
InputStream input = url.openStream();
ZipInputStream zipIn = new ZipInputStream(input);
ZipEntry entry;
while((entry = zipIn.getNextEntry()) != null) {
    InputStreamReader isr = new InputStreamReader(zipIn);
    CSVParser csv = new CSVParser(isr, CSVFormat.DEFAULT);
    List<CSVRecord> records = csv.getRecords(); <----- THIS IS WHERE IT HANGS!
}

出于某种原因,当CSVParser尝试读取文件时,我无法弄清楚它为什么会挂起。任何帮助是极大的赞赏!

P.S。:当它不是拉链时,我可以读取CSV,因此:

URL url = new URL(myURLString);
InputStream input = url.openStream();
InputStreamReader reader= new InputStreamReader(input );
CSVParser csv = new CSVParser(reader, CSVFormat.DEFAULT);
List<CSVRecord> records = csv.getRecords();
java apache csv zip
2个回答
0
投票

也许尝试使用不同的解析器。使用univocity-parsers可能会报告处理文件的任何错误。

只需改为:

URL url = new URL(myURLString);
InputStream input = url.openStream();
ZipInputStream zipIn = new ZipInputStream(input);
ZipEntry entry;
//configure the parser to detect the CSV format automatically
CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.detectFormatAutomatically();
//use this if the files are small (less than 50mb each)
//parserSettings.setReadInputOnSeparateThread(false);

CsvParser csv = new CsvParser(parserSettings);

while((entry = zipIn.getNextEntry()) != null) {
    InputStreamReader isr = new InputStreamReader(zipIn);
    List<Record> records = csv.parseAllRecords(isr);
}

希望能帮助到你。

免责声明:我是这个图书馆的作者。它是开源和免费的(Apache 2.0许可证)


0
投票

我写了一个库unzip-csv,它支持你的用例。它甚至可以解压缩归档中的特定文件(下载段),还支持多线程工作者。

© www.soinside.com 2019 - 2024. All rights reserved.