運行linux的shell命名文件
【一】java中運行shell命名api
有時候我們在Linux中運行Java程序時,需要調用一些Shell命令和腳本。而Runtime.getRuntime().exec()方法給我們提供了這個功能,而且Runtime.getRuntime()給我們提供了以下幾種exec()方法:
Process exec(String command)
在單獨的進程中執行指定的字符串命令。
Process exec(String[] cmdarray)
在單獨的進程中執行指定命令和變量。
Process exec(String[] cmdarray, String[] envp)
在指定環境的獨立進程中執行指定命令和變量。
Process exec(String[] cmdarray, String[] envp, File dir)
在指定環境和工作目錄的獨立進程中執行指定的命令和變量。
Process exec(String command, String[] envp)
在指定環境的單獨進程中執行指定的字符串命令。
Process exec(String command, String[] envp, File dir)
在有指定環境和工作目錄的獨立進程中執行指定的字符串命令。
ps:方法waitFor()
abstract int waitFor()
導致當前線程等待,如有必要,一直要等到由該 Process 對象表示的進程已經終止。
【二】構建shell腳本
創建echo.sh
#!/usr/bin/env bash
#輸出hello java
echo hello java
#創建hello.txt文件
touch hello.txt
#將"hello java"輸入到hello.txt文件中
echo hello java > hello.txt
【三】java代碼執行shell腳本
package com.shell;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* @author fengwen
*/
public class Main {
public static void main(String[] args) throws Exception {
//運行的命名
String bashCommand = "sh echo.sh";
Process pro = Runtime.getRuntime().exec(bashCommand);
//等待腳本執行完畢
int status = pro.waitFor();
if (status != 0) {
System.out.println("Failed to call shell's command ");
}
//輸出腳本運行的情況
BufferedReader reader = new BufferedReader(new InputStreamReader(pro.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
stringBuffer.append(line).append("\n");
}
System.out.println(stringBuffer.toString());
}
}