Java操作應(yīng)用——在Java中執(zhí)行某個(gè)shell命令
Java提供了Runtime類來(lái)執(zhí)行shell命令。由于這些是外部的命令,因此異常處理就顯得異常重要。在下面的例子中,我們將通過(guò)一個(gè)簡(jiǎn)單的例子來(lái)演示一下。我們會(huì)在shell命令行中打開一個(gè)pdf文件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; public class ShellCommandExec { public static void main(String[] args) { String gnomeOpenCommand = "gnome-open //home//user//Documents//MyDoc.pdf" ; try { Runtime rt = Runtime.getRuntime(); Process processObj = rt.exec(gnomeOpenCommand); InputStream stdin = processObj.getErrorStream(); InputStreamReader isr = new InputStreamReader(stdin); BufferedReader br = new BufferedReader(isr); String myoutput = "" ; while ((myoutput=br.readLine()) != null ) { myoutput = myoutput+ "/n" ; } System.out.println(myoutput); } catch (Exception e) { e.printStackTrace(); } } } |
點(diǎn)擊加載更多評(píng)論>>