RFT
RFT

Reputation: 1071

Name the Zip folder with the name of the zip file

I am using TarInputStream() to read the contents of a tar file and storing all the files from it at a particular location. I want to create a folder with the name similar to the tar file and save all my files in that folder. For example, if i have a tar file test.tar.gz with files test1 and test2 in it, my code should create a folder by the name test and extract the tar files to that folder.

Here is the code I have written.

TarInputStream tin = new TarInputStream(new GZIPInputStream(new FileInputStream(new File(tarFileName))));

TarEntry tarEntry = tin.getNextEntry();
        while (tarEntry != null) {// create a file with the same name as tar entry

            File destPath = new File(dest.toString() + File.separatorChar
                    + tarEntry.getName());

            FileOutputStream fout = new FileOutputStream(destPath);
                tin.copyEntryContents(fout);
                fout.close();
                ///services/advert/lpa/dimenions/data/advertiser/
                Path inputFile = new Path(destPath.getAbsolutePath());

                //To remove the local files set the flag to true
                fs.copyFromLocalFile(inputFile, filenamepath); 
                tarEntry = tin.getNextEntry();
}

Upvotes: 0

Views: 380

Answers (1)

ziesemer
ziesemer

Reputation: 28687

I'd change your new File(...) to new File(dest, tarEntry.getName()); (assuming dest is a File - can't see where it's coming from in your code).

And most importantly, you need to make sure that you're creating the directories you're trying to create the files in. This can be done by:

destPath.getParent().mkdirs();

The .getParent() is important, as we can't create a folder for each portion of the filename, otherwise the file name would also be created as a folder instead of a file, and then trying to write data to it would fail (as a file would be expected instead of the folder that would exist).

For obtaining the "base" lpa_1_454_20111117011749 name from something like lpa_1_454_20111117011749.tar.gz:

String tarFileName = "/tmp/lpa_1_454_20111117011749.tar.gz";

// Non-regular expression approach:
{
    int lastPath = tarFileName.lastIndexOf('/');
    if(lastPath >= 0){
        lastPath++;
    }
    int endName = tarFileName.length();
    if(tarFileName.endsWith(".tar.gz")){
        endName -= 7;
    }

    String baseName = tarFileName.substring(lastPath, endName);
    System.out.println(baseName);
}

// Regular expression approach:
{
    Pattern p = Pattern.compile("(?:.*/|^)(.*)\\.tar\\.gz");
    Matcher m = p.matcher(tarFileName);
    if(m.matches()){
        System.out.println(m.group(1));
    }
}

Either approach outputs:

lpa_1_454_20111117011749

Upvotes: 1

Related Questions