简体   繁体   English

Java中没有父文件夹的文件夹下的Tar文件

[英]Tar files under a folder without parent folder in java

I have the following file structure under c:\\Docs\\Desktop 我在c:\\ Docs \\ Desktop下具有以下文件结构

rootFolder
|_x1
  |_1.png
  |_2.png
|_x2

I have to traverse inside subfolders of rootFolder (x1, x2 ... xN) and create tar file that holds them. 我必须遍历rootFolder的子文件夹(x1,x2 ... xN)并创建包含它们的tar文件。 So x1.tar should have 1.png and 2.png 所以x1.tar应该有1.png和2.png

for(String folder: rootFolder.list()) {
    File files = new File(rootFolder.getAbsolutePath() + "\\" + folder);
    for(File subfiles : files.listFiles()) {
        fileList.add(subfiles);
    }
    generateTar(fileList,files.getAbsolutePath() + ".tar");
}

I am using org.apache.commons.compress.archivers inside generateTar method 我在generateTar方法中使用org.apache.commons.compress.archivers

generateTarFile(List<File> fileList, String tarName) {

    File tarFile = new File(tarName);
    OutputStream out = new FileOutputStream(tarFile);

    TarArchiveOutputStream aos = (TarArchiveOutputStream) new ArchiveStreamFactory().createArchiveOutputStream("tar", out);

    for(File file : fileList) {
        TarArchiveEntry entry = new TarArchiveEntry(file);
        entry.setSize(file.length());
        aos.putArchiveEntry(entry);
        IOUtils.copy(new FileInputStream(file), aos);
        aos.closeArchiveEntry();
    }

    aos.finish();
    aos.close();
    out.close();
}

This method creates a tar file with the same folder name (eg x1.tar under rootFolder), however x1.tar has the following structure 此方法创建具有相同文件夹名称的tar文件(例如rootFolder下的x1.tar),但是x1.tar具有以下结构

x1.tar
|_Docs
  |_Desktop
    |_rootFolder
      |_x1
        |_1.png
        |_2.png

instead of 代替

x1.tar
|_1.png
|_2.png

How can I achieve it? 我该如何实现?

You can set the name of the entry if you use the TarArchiveEntry constructor that accepts a name in addition to the file. 如果您使用的是TarArchiveEntry构造函数,该构造函数除了接受文件名之外,还可以接受名称,则可以设置条目的名称。 But that means you can't generate the tar from just a list of files: you'll need to somehow save the relative path while you walk the directory tree, or compute the relative path while you create the entries. 但这意味着您不能仅从文件列表中生成tar:您需要在遍历目录树时以某种方式保存相对路径,或者在创建条目时计算相对路径。

您可以通过在创建条目时使用文件名来实现此目的:

TarArchiveEntry entry = new TarArchiveEntry(file.getName());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM