参考博客:
Java调用Linux命令(cd的处理)
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class CmdTestThree {
public static void main(String[] args) {
CmdTestThree cmdTestThree = new CmdTestThree();
ArrayList<String> cmdList = new ArrayList<>();
// cmdList.add("firefox");
cmdList.add("cd /home/dj/test");
cmdList.add("pwd");
cmdList.add("touch 1.txt");
cmdList.add("echo \"Assess\" > 1.txt");
cmdList.add("touch 2.txt");
cmdList.add("touch 3.txt");
List<String> res = cmdTestThree.executeNewFlow(cmdList);
System.out.println("resaaa:" + res);
}
public List<String> executeNewFlow(List<String> commands) {
List<String> rspList = new ArrayList<String>();
Runtime run = Runtime.getRuntime();
try {
Process proc = run.exec("/bin/bash", null, null);
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
for (String line : commands) {
out.println(line);
}
// out.println("cd /home/test");
// out.println("pwd");
// out.println("rm -fr /home/proxy.log");
out.println("exit");// 这个命令必须执行,否则in流不结束。
String rspLine = "";
while ((rspLine = in.readLine()) != null) {
System.out.println(rspLine);
rspList.add(rspLine);
}
proc.waitFor();
in.close();
out.close();
proc.destroy();
} catch (IOException | InterruptedException e1) {
e1.printStackTrace();
}
return rspList;
}
}