![](/img/trans.png)
[英]How to make a Java Shell Command (NOT how to run a shell command with Java)
[英]How to run a shell command in the calling (current) shell with Java
假设是这样的:
execInCurrentShell("cd /")
System.out.println("Ran command : cd /")
在MyClass
的main()
function 中
这样当我运行 class 时,我cd
进入/
目录
user@comp [~] pwd
/Users/user
user@comp [~] java MyClass
Ran command : cd /
user@comp [/] pwd
/
运行shell命令的常用方式,即通过Runtime
class:
Runtime.getRuntime().exec("cd /")
在这里不起作用,因为它不在当前 shell 中运行命令,而是在新 shell 中运行命令。
execInCurrentShell()
function(实际工作的那个)会是什么样子?
您将无法运行影响当前调用 shell 的命令,只能从 Java 将命令行 bash/cmd 作为子进程运行并向它们发送命令,如下所示。 我不推荐这种方法:
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 程序启动一个命令 shell,你可以这样做:
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 使用相同的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.