UnTar and Upload a .tar.gz file maintaining the same folder structure in SpringBoot

101 Views Asked by At

I currently have a .tar.gz file with the following files and folders, that I am uploading using springboot

dir1/
    -file1
    dir2/
        -file2
        -file3
    dir3/
        -file4
        -file5

With my current code, I am able to extract all the files and add them to List<FileItem>

    private List<FileItem> unTarFile(MultipartFile file) throws Exception{
        List<FileItem> files = new ArrayList<FileItem>();
        
        InputStream in = file.getInputStream();
        GzipCompressorInputStream gzipIn = new GzipCompressorInputStream(in);
        TarArchiveInputStream tarIn = new TarArchiveInputStream(gzipIn);
        TarArchiveEntry entry;
        
        // Iterate over every entry in the TarArchive
        while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {

            String mimeType = URLConnection.guessContentTypeFromName(entry.getName());
            
            FileItem d = new DiskFileItem("fileData", mimeType, false, entry.getName(), (int) entry.getSize(), null);
            
            OutputStream dfos = d.getOutputStream();
            int size = (int) entry.getSize();
            byte[] buf = new byte[size];
            int readBytes = tarIn.read(buf, 0, size);
            dfos.write(buf);
            
            files.add(d);
        }
        return files;
    }

However, I would like to upload the file/s maintaining the same folder structure as the .tar.gz. Any suggestions how this can be done? I would still like to add it to List<FileItem> Thanks!

0

There are 0 best solutions below