Java 使用ProcessBuilder调用并执行windows和linux操作系统下的命令
Java 执行windows cmd copy 命令
public static void decompressionSubZipDirWin(List<String> zipPathList,String format){
try {
String command = "copy /B ";
for (int i = 0; i < zipPathList.size(); i++) {
zipPathList.set(i, zipPathList.get(i).replace("/","\\"));
}
command += zipPathList.get(0);
for (int i = 1; i < zipPathList.size(); i++) {
command += "+"+zipPathList.get(i);
}
command += " "+zipPathList.get(0).split("\\.")[0]+format;
System.out.println(command);
ProcessBuilder builder = new ProcessBuilder("cmd", "/c", command);
builder.redirectErrorStream(true);
Process process = builder.start();
process.waitFor();
int exitValue = process.exitValue();
log.info("命令执行完成,退出值: " + exitValue);
process.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
Java 执行linux bash cat命令
public static void decompressionSubZipDirLinux(List<String> zipPathList,String format){
String command = "cat";
try {
for (int i = 0; i < zipPathList.size(); i++) {
command += " "+zipPathList.get(i);
}
command += " >> "+zipPathList.get(0).split("\\.")[0]+format;
if (!new File(zipPathList.get(0).split("\\.")[0]+format).exists()){
new File(zipPathList.get(0).split("\\.")[0]+format).createNewFile();
}
log.info("命令:"+command);
ProcessBuilder builder = new ProcessBuilder();
builder.redirectErrorStream(true);
builder.command("bash","-c",command);
Process process = builder.start();
process.waitFor();
int exitValue = process.exitValue();
System.out.println("Exited with error code : " + exitValue);
process.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}