gpt4 book ai didi

java - 读取 tar.gz 存档中 CSV 文件的内容

转载 作者:太空宇宙 更新时间:2023-11-04 09:45:40 26 4
gpt4 key购买 nike

我想将 tar.gz 存档的内容保存在数据库表中。

存档包含 CSV 格式的 txt 文件。

这个想法是在数据库中为 txt 文件中的每一行插入一个新行。

问题是我无法单独读取文件的内容然后转到下一个文件。

下面的EntryTableEntryTableLine是Hibernate实体。

EntryTableEntryTableLine 处于 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() 为 null。

假设我的存档中有 4 个文件。每个文件内有 3 行。然而,在数据库中,有些条目有 5 行,而有些则没有。

谢谢!

最佳答案

您可以使用 Apache Commons CompressTarArchiveInputStream如下图( Reference ):

TarArchiveInputStream input = new TarArchiveInputStream(new GzipCompressorInputStream(new FileInputStream("C:\\Users\\User\\Desktop\\Books\\test\\CoverLetter-Version2.gz")));
TarArchiveEntry entry = input.getNextTarEntry();
System.out.println(entry.getName()); // prints the name of file inside the tar
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
while (entry != null) {
br = new BufferedReader(new InputStreamReader(input)); // Read directly from tarInput
System.out.println("For File = " + currentEntry.getName());
String line;
while ((line = br.readLine()) != null) {
System.out.println("line="+line);
}
entry = input.getNextTarEntry();
}

关于java - 读取 tar.gz 存档中 CSV 文件的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55456671/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com