Search code examples
command-linejavaziprar

Unzip all file without it's folder using Java


Is it possible to unzip all files from the zip folder without its folder?

Example:

zipfolder.zip has two subfolders called folder1(having files like 1.txt, 2.xlsx, 3.pdf) and folder2(having files like 4.txt, 5.pdf)

Note: The source can any type of archive files like .zip, .rar, .tar, .7-zip etc

This is my code:

String sevenZipLocation = "C:\\Program Files\\7-Zip\\7z.exe";
String src = source filepath (zip file)
String target = output path (output path)

String[] command={sevenZipLocation,"x",src,"-o"+target,"-aou","-y"};

ProcessBuilder p = new ProcessBuilder( command );
Process process = p.start();

InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);

@SuppressWarnings("unused")
String line;

while ((line = br.readLine()) != null){
    System.out.println("line1 "+line);
}
process.waitFor();

When I execute this code the output like

unzip folder ----- folder1(having files like 1.txt, 2.xlsx, 3.pdf) and folder2(having files like 4.txt, 5.pdf)

But I want to extract the only file from all folders and the output like 1.txt, 2.xlsx, 3.pdf, 4.txt, 5.pdf in the output path.

Is there any command for that. Thanks.


Solution

  • All you need to change:

    String[] command={sevenZipLocation,"e",src,"-o"+target,"-aou","-y","*.*","-r"};
    

    PS. I don't think Java is the best choice to run OS commands. You'll be wasting a lot of time. But if you insist, don't forget there might be an errorstream too.