如何使用Java在调用(当前)shell中运行shell命令

假设像这样:

execInCurrentShell("cd /")
System.out.println("Ran command : cd /")

位于main()的{​​{1}}函数中

因此,当我运行课程时,我MyClass进入了cd目录

/

运行shell命令的常用方法,即通过user@comp [~] pwd /Users/user user@comp [~] java MyClass Ran command : cd / user@comp [/] pwd / 类:

Runtime

在这里不起作用,因为它不会在当前shell中运行命令,而是在新shell中运行命令。

Runtime.getRuntime().exec("cd /") 函数(实际起作用的函数)是什么样的?

iCMS 回答:如何使用Java在调用(当前)shell中运行shell命令

您将无法运行影响当前调用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

大家都在问