[英]Command to unzip a specific folder using 7zip
I am working with windows to be more specific, I am invoking the cmd
Command from java program using process and getRuntime().exec()
. 我正在使用Windows进行更具体的工作,我正在使用process和
getRuntime().exec()
从Java程序调用cmd
命令。 I tried options like -r
but its not working. 我尝试了
-r
选项,但不起作用。 I tried the code line 我尝试了代码行
Process proc = prog.exec(System.getenv("ProgramFiles").concat("\\7-Zip\\7z x " + "\""+inputZIPFile+"\""+ " -o"+outputFolder+"SpecificFolder\\* -r"));
Thanks in advance 提前致谢
Start by using ProcessBuilder
instead. 首先使用
ProcessBuilder
开始。 It handles parameters with spaces better and allows you do things like redirect the output stream and specify the starting directory for the command... 它可以更好地处理带有空格的参数,并允许您执行诸如重定向输出流和为命令指定起始目录之类的事情。
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("");
}
}
You might also want to consider Apache Commons Compress which provides read support for 7zip 您可能还需要考虑使用Apache Commons Compress ,它提供对7zip的读取支持
Why not unzip using java? 为什么不使用Java解压缩? From Compressing and Decompressing Data Using Java APIs :
使用Java API压缩和解压缩数据 :
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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.