以下 Main.java 代碼只是嘗試模擬以下 linux 命令:
cd /dir1/dir2
./shellScript.sh
以下程式僅在可執行檔案 Main.jar 位于/ dir1/dir2 內而不是 /dir1/dir2 外時才有效。如何修改下面的程式以便 Main.jar 可以位于檔案系統的任何位置?
public class Main {
public static String runCmdLineProcess(String commandStr){
String returnVal = "";
Runtime r = Runtime.getRuntime();
try {
Process p = r.exec(commandStr);
BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = b.readLine()) != null){
returnVal = line "\n";
}
}
catch(IOException ex){
ex.printStackTrace();
}
return returnVal;
}
public static void runProcessBuilder(String scriptPath){
String[] cmd = {scriptPath};
try {
runCmdLineProcess("cd /dir1/dir2");
Runtime.getRuntime().exec(cmd);
}
catch (IOException ex){
ex.printStackTrace();
}
}
public static void main(String[] args){
runProcessBuilder("./shellScript.sh"); // <-- works if I run from inside "/dir1/dir2".
//But if I'm outside "dir2", get an error message
// saying "Cannot run program "./shellScript.sh": error = 2, No such file or directory
}
}
uj5u.com熱心網友回復:
您應該使用ProcessBuilder啟動或多載之一exec。您需要指定腳本的路徑名并傳遞與當前目錄相同的路徑名來運行腳本:
File pwd = new File("/dir1/dir2");
String shell = new File(pwd, "shellScript.sh").toString();
ProcessBuilder pb = new ProcessBuilder(shell);
// No STDERR => merge to STDOUT - or call redirectError(File)
pb.redirectErrorStream(true);
// Set CWD for the script
pb.directory(pwd);
Process p = pb.start();
// Move STDOUT to the output stream (or original code to save as String)
try(var stdo = p.getInputStream()) {
stdo.transferTo(stdout);
}
int rc = p.waitFor();
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/445112.html
