在Java中,可以透過
Runtime類別
或ProcessBuilder類別
來實作呼叫外部程式。
使用Runtime類別:
Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec("外部程序路径");
使用ProcessBuilder類別:
ProcessBuilder builder = new ProcessBuilder("外部程序路径"); Process process = builder.start();
#以上兩種方法均可啟動一個外部進程。如果需要向外部進程傳遞參數,可以在exec() 或ProcessBuilder建構子中傳遞字串陣列
String[] cmdarray = {"外部程序路径", "参数1", "参数2"};Process process = runtime.exec(cmdarray);
##外部進程的傳回結果可以通過process物件取得。可以使用getInputStream() 方法讀取外部程序的標準輸出流,或使用getErrorStream() 方法讀取錯誤輸出流。InputStream inputStream = process.getInputStream(); // 标准输出流 InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); // 输出每行结果 }登入後複製
注意:在呼叫外部程式時一定要小心,因為它可能會造成安全問題和系統崩潰等異常情況。建議使用此功能時對外部程式進行充分的測試和驗證
@Test public void runtimeTest() { try { //获取执行进程 Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec("ipconfig"); //读取输入流 InputStream inputStream = process.getInputStream(); //将字节流转成字符流 InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "gbk"); //字符缓冲区 char[] c = new char[1024]; int len = -1; while ((len = inputStreamReader.read(c)) != -1) { String s = new String(c, 0, len); System.out.print(s); } inputStream.close(); inputStreamReader.close(); //阻塞当前线程,直到进程退出为止 process.waitFor(); int exitValue = process.exitValue(); if (exitValue == 0) { System.out.println("进程正常结束"); } else { System.out.println("进程异常结束"); } } catch (Exception e) { e.printStackTrace(); } }
@Test public void processBuilderTest1() { ProcessBuilder processBuilder = new ProcessBuilder(); processBuilder.command("java"); //将标准输入流和错误输入流合并,通过标准输入流读取信息 processBuilder.redirectErrorStream(true); try { //启动进程 Process start = processBuilder.start(); //获取输入流 InputStream inputStream = start.getInputStream(); //转成字符输入流 InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "gbk"); int len = -1; //字符缓冲区 char[] c = new char[1024]; //读取进程输入流中的内容 while ((len = inputStreamReader.read(c)) !=-1){ String s = new String(c, 0, len); System.out.print(s); } inputStreamReader.close(); inputStream.close(); //阻塞当前线程,直到进程退出为止 start.waitFor(); int exitValue = start.exitValue(); if (exitValue == 0) { System.out.println("进程正常结束"); } else { System.out.println("进程异常结束"); } } catch (IOException e) { e.printStackTrace(); } }
processBuilder.command("java","-version");
List<String> command = new ArrayList<>(); command.add("java"); command.add("-version"); processBuilder.command(command);
Apache Commons Exec 是一個用於執行外部進程的Java 庫,可以方便地啟動和控制進程,並且提供了對輸入、輸出流的管理和處理使用步驟介紹1.新增依賴,將Apache Commons Exec庫加入專案中
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-exec</artifactId> <version>1.3</version> </dependency>
CommandLine cmdLine = CommandLine.parse("command argument1 argument2");
DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(new File("/your/workdir"));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler);
executor.execute(cmdLine); String output = outputStream.toString("UTF-8"); System.out.println(output);
public static void main(String[] args) throws IOException { CommandLine cmdLine = CommandLine.parse("java -version"); DefaultExecutor executor = new DefaultExecutor(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); executor.execute(cmdLine); String output = outputStream.toString("UTF-8"); System.out.println(output); }
java version "1.8.0_271"Java(TM) SE Runtime Environment (build 1.8. 0_271-b09)
#
Java HotSpot(TM) 64-Bit Server VM (build 25.271-b09, mixed mode)
以上是Java怎麼實作呼叫外部程式的詳細內容。更多資訊請關注PHP中文網其他相關文章!