您将无法运行影响当前调用shell的命令,而只能将命令行bash / cmd作为Java的子进程运行,并按以下方式发送命令。我不推荐这种方法:
String[] cmd = new String[] { "/bin/bash" }; // "CMD.EXE"
ProcessBuilder pb = new ProcessBuilder(cmd);
Path out = Path.of(cmd[0]+"-stdout.log");
Path err = Path.of(cmd[0]+"-stderr.log");
pb.redirectOutput(out.toFile());
pb.redirectError(err.toFile());
Process p = pb.start();
String lineSep = System.lineSeparator();
try(PrintStream stdin = new PrintStream(p.getOutputStream(),true))
{
stdin.print("pwd");
stdin.print(lineSep);
stdin.print("cd ..");
stdin.print(lineSep);
stdin.print("pwd");
stdin.print(lineSep);
};
p.waitFor();
System.out.println("OUTPUT:"+Files.readString(out));
System.out.println("ERROR WAS: "+Files.readString(err));
}
这也适用于Windows上的CMD.EXE(使用不同的命令)。要捕获每个命令的响应,如果确实需要每行而不是一个文件,则应将pb.redirectOutput()
的使用替换为代码以读取pb.getInputStream()。
,
在Windows上从Java程序启动命令外壳程序,您可以按以下步骤操作:
import java.io.IOException;
public class Command {
public static void main(String[] args) {
try {
Runtime.getRuntime().exec("cmd.exe /c start");
} catch (IOException e) {
e.printStackTrace();
}
}
}
对于Linux,您需要使用相同的方法。
本文链接:https://www.f2er.com/1867230.html