[英]Running Bash commands in Java
我有以下 class。 它允許我通過 java 執行命令。
public class ExecuteShellCommand {
public String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
}
當我運行命令時,不會保存上一個命令的結果。 例如:
public static void main(String args[]) {
ExecuteShellCommand com = new ExecuteShellCommand();
System.out.println(com.executeCommand("ls"));
System.out.println(com.executeCommand("cd bin"));
System.out.println(com.executeCommand("ls"));
}
給出 output:
bin
src
bin
src
為什么第二個“ls”命令不顯示“bin”目錄的內容?
使用Runtime.exec(command)
啟動新進程。 每個進程都有一個工作目錄。 這通常是啟動父進程的目錄,但您可以更改進程啟動的目錄。
我建議使用ProcessBuilder
ProcessBuilder pb = new ProcessBuilder("ls");
pb.inheritIO();
pb.directory(new File("bin"));
pb.start();
如果要在shell中運行多個命令,最好創建一個臨時shell腳本並運行它。
public void executeCommands() throws IOException {
File tempScript = createTempScript();
try {
ProcessBuilder pb = new ProcessBuilder("bash", tempScript.toString());
pb.inheritIO();
Process process = pb.start();
process.waitFor();
} finally {
tempScript.delete();
}
}
public File createTempScript() throws IOException {
File tempScript = File.createTempFile("script", null);
Writer streamWriter = new OutputStreamWriter(new FileOutputStream(
tempScript));
PrintWriter printWriter = new PrintWriter(streamWriter);
printWriter.println("#!/bin/bash");
printWriter.println("cd bin");
printWriter.println("ls");
printWriter.close();
return tempScript;
}
當然,您也可以在系統上使用任何其他腳本。 在運行時生成腳本有時會有意義,例如,如果執行的命令必須更改。 但是您應該首先嘗試創建一個可以使用參數調用的腳本,而不是在運行時動態生成它。
如果腳本生成很復雜,使用像velocity這樣的模板引擎也可能是合理的。
你可以形成一個復雜的bash命令來執行所有操作:“ls; cd bin; ls”。 要完成這項工作,您需要顯式調用bash。 這種方法應該為您提供bash命令行的所有功能(報價處理,$擴展,管道等)。
/**
* Execute a bash command. We can handle complex bash commands including
* multiple executions (; | && ||), quotes, expansions ($), escapes (\), e.g.:
* "cd /abc/def; mv ghi 'older ghi '$(whoami)"
* @param command
* @return true if bash got started, but your command may have failed.
*/
public static boolean executeBashCommand(String command) {
boolean success = false;
System.out.println("Executing BASH command:\n " + command);
Runtime r = Runtime.getRuntime();
// Use bash -c so we can handle things like multi commands separated by ; and
// things like quotes, $, |, and \. My tests show that command comes as
// one argument to bash, so we do not need to quote it to make it one thing.
// Also, exec may object if it does not have an executable file as the first thing,
// so having bash here makes it happy provided bash is installed and in path.
String[] commands = {"bash", "-c", command};
try {
Process p = r.exec(commands);
p.waitFor();
BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = b.readLine()) != null) {
System.out.println(line);
}
b.close();
success = true;
} catch (Exception e) {
System.err.println("Failed to execute bash with command: " + command);
e.printStackTrace();
}
return success;
}
每次調用都在它自己的shell中執行。 因此第三次調用的“cd”沒有被第三次調用看到。
請參閱: https : //docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exec(java.lang.String) 。
這表明該命令在單獨的進程中運行。 因此,您產生了3個進程。
如果你想在同一個過程中全部3,請嘗試這樣:
com.executeCommand("ls; cd bin; ls");
你運行的每個命令都有自己的bash shell,所以一旦你cd到那個目錄,下一個命令你打開新的bash shell
嘗試將命令更改為
ls bin
每個命令都是單獨執行的。 他們不同意上下文。
你可以使用bash命令“pmset -g batt”,就像下面的方法一樣,返回電池百分比
public int getPercentage() {
Process process = null;
try {
process = Runtime.getRuntime().exec("pmset -g batt");
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String s = null;
String y = "";
while (true) {
try {
if (!((s = reader.readLine()) != null)) break;
} catch (IOException e) {
e.printStackTrace();
}
y += s;
System.out.println("Script output: " + s);
}
return Integer.parseInt(y.substring(y.indexOf(')') + 2, y.indexOf('%')));
}
供將來參考:在cd之后運行bash命令,在子目錄中:
import java.io.BufferedReader;
import java.io.InputStreamReader;
/*
$ ( D=somewhere/else ; mkdir -p $D ; cd $D ; touch file1 file2 ; )
$ javac BashCdTest.java && java BashCdTest
.. stdout: -rw-r--r-- 1 ubuntu ubuntu 0 Dec 28 12:47 file1
.. stdout: -rw-r--r-- 1 ubuntu ubuntu 0 Dec 28 12:47 file2
.. stderr: /bin/ls: cannot access isnt_there: No such file or directory
.. exit code:2
*/
class BashCdTest
{
static void execCommand(String[] commandArr)
{
String line;
try
{
Process p = Runtime.getRuntime().exec(commandArr);
BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = stdoutReader.readLine()) != null) {
// process procs standard output here
System.out.println(" .. stdout: "+line);
}
BufferedReader stderrReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = stderrReader.readLine()) != null) {
// process procs standard error here
System.err.println(" .. stderr: "+line);
}
int retValue = p.waitFor();
System.out.println(" .. exit code:"+Integer.toString(retValue));
}
catch(Exception e)
{ System.err.println(e.toString()); }
}
public static void main(String[] args)
{
String flist = "file1 file2 isnt_there";
String outputDir = "./somewhere/else";
String[] cmd = {
"/bin/bash", "-c",
"cd "+outputDir+" && /bin/ls -l "+flist+" && /bin/rm "+flist
};
execCommand(cmd);
}
}
這對我有用。
public static void executeBashCommand(String command) throws IOException, InterruptedException
{
new ProcessBuilder("/bin/bash", "-c", command).inheritIO().start().waitFor();
}
並按照 package 導入。
import java.io.IOException;
並將主 function 更改為此。
public static void main(String args[]) throws Exception
例子:-
executeBashCommand("ls");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.