Akshatha S M
Akshatha S M

Reputation: 1

How to zip each text files individually

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();
}

Upvotes: 0

Views: 49

Answers (2)

Jiya
Jiya

Reputation: 875

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);
    }
}

Upvotes: 1

Joop Eggen
Joop Eggen

Reputation: 109567

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 produce 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);
    }        
}

Upvotes: 1

Related Questions