Home > Mobile >  How to zip each text files individually
How to zip each text files individually

Time:11-30

This code is to zip all text files into one zip folder. I want to zip each text files in a separate zip using winzip commands in my java code. How can I do that?

Runtime rt = Runtime.getRuntime();
        //updateEnv();
        System.out.println("Zipping file");
        String[] command = {"C:\\Program Files\\WinZip\\winzip64","-a","-r","-en","zippedfile.zip", "*.txt" };
        try {
            rt.exec(command);
            System.out.println("Zipped file");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

CodePudding user response:

This works fine.

File[] files = new File("C:\\Users\\user\\Desktop\\test").listFiles();
for (File file : files) {
    if (file.isFile() && file.getName().endsWith(".txt")) {
        String[] command = {"C:\\Program Files\\WinZip\\winzip64","-a","-r","-en",file.getName()   ".zip", file.getName() };
        rt.exec(command);
    }
}

CodePudding user response:

I wanted to mention a variation:

When wanting each file compressed separately - as a separate new file -, then gzip is usual, at least under Unix/Linux.

So README.txt will become README.txt.gz. WinZip or 7Zip will handle those files too.

As java already has the means to compress, here an immediate version:

private static void main(String[] args) throws IOException {
    Path dir = Paths.get("C:/Users/.../Documents");
    Path gzDir = Paths.get("C:/Users/.../Documents/gz");
    Files.createDirectories(gzDir);
    Files.list(dir)
            .filter(f -> f.getFileName().toString().endsWith(".txt"))
            .forEach(f -> gzCompress(f, gzDir));
}

private static void gzCompress(Path file, Path gzDir) {
    Path gzFile = gzDir.resolve(file.getFileName().toString()   ".gz");
    try (FileInputStream fis = new FileInputStream(file.toFile());
            FileOutputStream fos = new FileOutputStream(gzFile.toFile());
            GZIPOutputStream gzos = new GZIPOutputStream(fos)) {
        fis.transferTo(gzos);
    } catch (IOException e) {
        System.getLogger(App.class.getName()).log(System.Logger.Level.ALL, e);
    }        
}
  •  Tags:  
  • java
  • Related