使用7zip解压缩特定文件夹的命令

时间:2014-07-02 06:08:07

标签: java windows 7zip

我正在使用windows更具体,我正在使用进程和cmd从java程序调用{​​{1}}命令。我尝试过像getRuntime().exec()这样的选项,但它不起作用。我尝试了代码行

-r

提前致谢

2 个答案:

答案 0 :(得分:0)

首先使用ProcessBuilder。它可以更好地处理带有空格的参数,并允许您执行重定向输出流和指定命令的起始目录等操作...

public static void main(String[] args) {
    ProcessBuilder pb = new ProcessBuilder(
        System.getenv("ProgramFiles") + "/7-Zip/7z.exe",
            "x",
            inputZIPFile,
            "-o" + outputFolder+"/SpecificFolder",
            "-r"
    );
    pb.redirectError();
    try {
        Process p = pb.start();
        new Thread(new InputConsumer(p.getInputStream())).start();
        System.out.println("Exited with: " + p.waitFor());
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

public static  class InputConsumer implements Runnable {
    private InputStream is;

    public InputConsumer(InputStream is) {
        this.is = is;
    }

    @Override
    public void run() {
        try {
            int value = -1;
            while ((value = is.read()) != -1) {
                System.out.print((char) value);
            }
        } catch (IOException exp) {
            exp.printStackTrace();
        }
        System.out.println("");
    }

}

您可能还想考虑提供7zip

的读取支持的Apache Commons Compress

答案 1 :(得分:0)

为什么不用java解压缩?来自Compressing and Decompressing Data Using Java APIs

import java.io.*;
import java.util.zip.*;

public class UnZip {
   final int BUFFER = 2048;
   public static void main (String argv[]) {
      try {
         BufferedOutputStream dest = null;
         FileInputStream fis = new 
       FileInputStream(argv[0]);
         ZipInputStream zis = new 
       ZipInputStream(new BufferedInputStream(fis));
         ZipEntry entry;
         while((entry = zis.getNextEntry()) != null) {
            System.out.println("Extracting: " +entry);
            int count;
            byte data[] = new byte[BUFFER];
            // write the files to the disk
            FileOutputStream fos = new 
          FileOutputStream(entry.getName());
            dest = new 
              BufferedOutputStream(fos, BUFFER);
            while ((count = zis.read(data, 0, BUFFER)) 
              != -1) {
               dest.write(data, 0, count);
            }
            dest.flush();
            dest.close();
         }
         zis.close();
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}