[英]Linux terminal command execution with java
我的程序需要幫助。 我要做的是,當我單擊一個按鈕時,我的 java 程序將必須在 linux 終端上執行命令,如下所示,然后必須關閉程序。
String com1 = "rm -r /home/ctm-tech/Documenti/App/Thermaskin";
String com2 = "cp -r /media/ctm-tech/FXPoWer_1/Thermaskin /home/ctm-tech/Documenti/App/";
String com3 = "java -jar /home/ctm-tech/Documenti/App/Thermaskin/dist/Thermaskin.jar";
String com4 = "sudo eject /media/ctm-tech/FXPoWer_1";
try {
Process p1 = Runtime.getRuntime().exec(com1);
Process p2 = Runtime.getRuntime().exec(com2);
Process p3 = Runtime.getRuntime().exec(com3);
Process p4 = Runtime.getRuntime().exec(com4);
} catch (IOException e) {
System.out.println("Qualcosa è andato storto" + e.toString());
}
try {
Thread.sleep(6000);
} catch (InterruptedException ex) {}
System.exit(0);
問題是我的程序只執行第一個命令,有時它什么也不執行。
這些命令必須更新正在運行的程序,並在 FXPoWer_1 pendrive 中提供更高版本。
有人能幫我嗎? 非常感謝,等待回復
“Some Programmers Dude”的新聞 這是現在的代碼
private void jButton_aggiornaActionPerformed(java.awt.event.ActionEvent evt) {
runCommand("cp -r /media/ctm-tech/FXPoWer_1/Thermaskin1 /home/ctm-tech/Documenti/App/");
runCommand("java -jar /home/ctm-tech/Documenti/App/Thermaskin1/dist/Thermaskin.jar");
runCommand("rm -r /home/ctm-tech/Documenti/App/Thermaskin");
runCommand("mv /home/ctm-tech/Documenti/App/Thermaskin1 /home/ctm-tech/Documenti/App/Thermaskin");
runCommand("sudo eject /media/ctm-tech/FXPoWer_1");
System.exit(0);
}
您嘗試運行的命令將全部並行運行,而無法控制先運行的命令或它們的順序。
這意味着如果以錯誤的順序發生,某些命令可能(並且將會)失敗。
解決它的一種簡單方法是在Process
object 上調用waitFor
,等待每個命令完成后再開始下一個命令。
我建議您創建一個新的 function 來運行命令並等待它完成:
private void runCommand(String command) {
try {
Process proc = Runtime.getRuntime().exec(command);
// Wait for command to finish
proc.waitFor();
} catch (IOException e) {
System.out.println("Error running command: " + e.toString());
}
}
然后你可以為你的每個命令調用它:
runCommand("rm -r /home/ctm-tech/Documenti/App/Thermaskin");
runCommand("cp -r /media/ctm-tech/FXPoWer_1/Thermaskin /home/ctm-tech/Documenti/App/");
runCommand("java -jar /home/ctm-tech/Documenti/App/Thermaskin/dist/Thermaskin.jar");
runCommand("sudo eject /media/ctm-tech/FXPoWer_1");
這些命令現在將按照調用的確切順序運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.