Java 透過 Runtime.exec() 啟動外部程序,返回 Process 物件,可控制輸入/輸出/錯誤流、等待結束、獲取退出碼。
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(); }
}
public static void main(String[] args) {
String projectDir = System.getProperty("user.dir"); // 專案根目錄
File dir = new File(projectDir, "hello");
dir.mkdirs();
}
File dir = new File("."); // 相對路徑
String canonicalPath = dir.getCanonicalPath(); // 解析為絕對路徑
// 或
String classPath = MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath();
<%@ 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 模式)。cmd.exe /c,Linux/Mac 直接用命令陣列 new String[]{"/bin/sh","-c","cmd"} 或 Runtime.exec(String[])。ProcessBuilder (Java 5+) 設定環境、工作目錄、重導向。ProcessBuilder pb = new ProcessBuilder("ping", "www.google.com");
pb.directory(new File("/tmp")); // 設定工作目錄
pb.redirectErrorStream(true); // 合併錯誤流到標準輸出
Process p = pb.start();
// 處理輸出流...