首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 執行系統命令完全指南:Runtime.exec、Process 處理、路徑獲取與 JSP 中調用 Ping 實戰

     編輯:Java 相關知識

核心 API:Runtime.getRuntime().exec()

Java 透過 Runtime.exec() 啟動外部程序,返回 Process 物件,可控制輸入/輸出/錯誤流、等待結束、獲取退出碼。

常見用法範例

1. 啟動瀏覽器開啟網址 / 執行 Ping

public class TestCmd {
    public static void main(String[] args) {
        try {
            // Windows: 開啟預設瀏覽器
            Runtime.getRuntime().exec("cmd.exe /c start https://www.csdn.net");
            // 執行 ping(需處理輸出流防止阻塞)
            Process p = Runtime.getRuntime().exec("cmd.exe /c ping 10.144.98.100");
            // 必須消費輸出流,否則緩衝區滿導致進程掛起
            StreamGobbler.gobble(p.getInputStream(), System.out);
            StreamGobbler.gobble(p.getErrorStream(), System.err);
            p.waitFor();
        } catch (Exception e) { e.printStackTrace(); }
    }
}

// 輔助類:非阻塞消費流
class StreamGobbler extends Thread {
    InputStream is; OutputStream os;
    StreamGobbler(InputStream is, OutputStream os) { this.is=is; this.os=os; }
    public void run() {
        try { byte[] buf=new byte[1024]; int len; while((len=is.read(buf))!=-1) os.write(buf,0,len); }
        catch(IOException ignored) {}
    }
    static void gobble(InputStream is, OutputStream os) { new StreamGobbler(is,os).start(); }
}

2. 在專案目錄下建立資料夾

public static void main(String[] args) {
    String projectDir = System.getProperty("user.dir"); // 專案根目錄
    File dir = new File(projectDir, "hello");
    dir.mkdirs();
}

3. 獲取當前類檔案絕對路徑

File dir = new File("."); // 相對路徑
String canonicalPath = dir.getCanonicalPath(); // 解析為絕對路徑
// 或
String classPath = MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath();

JSP 中調用 Ping 並即時顯示結果

<%@ page import="java.io.*" contentType="text/html; charset=GB2312" %>
<h2>Ping 測試頁面</h2>
<%
    String ip = "www.sina.com.cn";
    Process process = Runtime.getRuntime().exec("ping " + ip);
    BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line;
    out.println("<pre>");
    while ((line = br.readLine()) != null) {
        out.println(line);
        out.flush(); // 關鍵:即時推送到瀏覽器
    }
    out.println("</pre>");
    br.close();
    process.waitFor();
%>

關鍵最佳實踐

  • 必須消費輸出/錯誤流:否則子進程緩衝區填滿導致死鎖(參考 StreamGobbler 模式)。
  • 跨平台命令差異:Windows 用 cmd.exe /c,Linux/Mac 直接用命令陣列 new String[]{"/bin/sh","-c","cmd"} 或 Runtime.exec(String[])。
  • 安全性:避免拼接用戶輸入構造命令,防止命令注入;優先使用 ProcessBuilder (Java 5+) 設定環境、工作目錄、重導向。
  • JSP 執行長時間命令:需注意 Servlet 容器請求超時設定,長任務建議異步處理(啟動線程、返回任務 ID、前端輪詢)。

進階:ProcessBuilder (Java 5+)

ProcessBuilder pb = new ProcessBuilder("ping", "www.google.com");
pb.directory(new File("/tmp")); // 設定工作目錄
pb.redirectErrorStream(true);   // 合併錯誤流到標準輸出
Process p = pb.start();
// 處理輸出流...
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved