【发布时间】:2019-04-01 13:45:15
【问题描述】:
我想将 tar.gz 存档的内容保存在数据库表中。
存档包含 CSV 格式的 txt 文件。
这个想法是为 txt 文件中的每一行在数据库中插入一个新行。
问题是我不能单独读取一个文件的内容然后继续下一个文件。
EntryTable 和 EntryTableLine 下面是 Hibernate 实体。
EntryTable 与 EntryTableLine 处于 OneToMany 关系(一个文件 -EntryTable- 可以有很多行 -EntryTableLine-)。
public static final int TAB = 9;
FileInputStream fileInputStream = new FileInputStream(fileLocation);
GZIPInputStream gzipInputStream = new GZIPInputStream(fileInputStream);
TarArchiveInputStream tar = new TarArchiveInputStream(gzipInputStream);
BufferedReader reader = new BufferedReader(new InputStreamReader(tar));
// Columns are delimited with TAB
CSVFormat csvFormat = CSVFormat.TDF.withHeader().withDelimeter((char) TAB);
CSVParser parser = new CSVParser(reader, csvFormat);
TarArchiveEntry tarEntry = tar.getNextTarEntry();
while(tarEntry != null){
EntryTable entryTable = new EntryTable();
entryTable.setFilename(tarEntry.getName());
if(reader != null){
// Here is the problem
for(CSVRecord record : parser){
//this could have been a StringBuffer
String line;
int i = 1;
for(String val : record){
line = "<column" + i + ">" + val + "</column" + i + ">";
}
EntryTableLine entryTableLine = new EntryTableLine();
entryTableLine.setContent(line);
entryDao.saveLine(entryTableLine);
}
}
tarEntry = tar.getNextTarEntry();
}
我尝试将 tarEntry.getFile() 转换为 InputStream,但不幸的是 tarEntry.getFile() 为空。
假设我在存档中有 4 个文件。每个文件里面有 3 行。但是,在数据库中,有些条目有 5 行,而有些则没有。
谢谢!
【问题讨论】:
-
我相信您需要在每次调用 getNextTarEntry 后从 TarArchiveInputStream 中读取数据。
-
正如TarArchiveEntry.getFile() 的文档所述:“此方法仅适用于从文件创建的条目,但不适用于从存档读取的条目。”。文档的示例页面包含一些代码how to read a TAR archive。
-
我没有正确读取 InputStream。在执行类似于示例“如何读取 TAR 存档”的操作后,我设法读取了每个文件的内容。谢谢:D
标签: java hibernate apache-commons-compress