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

标签 java hibernate apache-commons-compress

我想将 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/

相关文章:

java - Hibernate:级联问题

java - Apache Commons 压缩无法解析 Android N 之前的 SeekableInMemoryByteChannel 类

java - 将 SQL/plPGsql 测试移植到 Java/JDBC : test an exception

java - org.springframework.beans.factory.BeanCreationException :

java - 扫描仪问题,输入信息不起作用

java - org.hibernate.MappingNotFoundException : resource: hibernate. cfg.xml 未找到

java - 为 ServletOutputStream 创建包含多个 zip 的单个 zip 失败

java - Apache Commons compress - 分割 Zip 文件

java - 如何检查客户端是否在Java中是本地的

java - 更新写入 java 文本文件的对象