簡體   English   中英

如何在調用(當前)shell 和 Java 中運行 shell 命令

[英]How to run a shell command in the calling (current) shell with Java

假設是這樣的:

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

MyClassmain() 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM