目錄
Using ProcessBuilder (Recommended)
Handling Errors and Input
Security and Best Practices
首頁 Java java教程 如何從Java運行命令行命令

如何從Java運行命令行命令

Aug 16, 2025 am 11:52 AM
java 命令列

使用Runtime.exec()可執行外部命令,但需用字符串數組避免空格問題;2. 推薦使用ProcessBuilder,因其更靈活,可設置環境變量、工作目錄且語法清晰;3. 應同時讀取stdout和stderr並處理輸入輸出流;4. 避免命令注入,妥善處理異常和流關閉;5. 注意命令的平台依賴性,新代碼應優先使用ProcessBuilder以確保安全性和可維護性。

How to run a command line command from Java

You can run a command line command from Java using the Runtime.exec() method or the ProcessBuilder class. Both approaches allow you to execute external system commands and interact with their input/output streams. Here's how to use each method effectively.


Using Runtime.getRuntime().exec()

This is the traditional way to run external commands.

 import java.io.BufferedReader;
import java.io.InputStreamReader;

public class RunCommand {
    public static void main(String[] args) {
        try {
            // Example: Run 'ls -l' on Linux/Mac or 'dir' on Windows
            Process process = Runtime.getRuntime().exec("ls -l");

            // Read the output
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream())
            );

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // Wait for the command to finish
            int exitCode = process.waitFor();
            System.out.println("Command exited with code: " exitCode);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Notes:

  • Pass the command as a string or a string array (recommended for arguments with spaces).
  • Use a string array to avoid issues with spaces and special characters:
     Runtime.getRuntime().exec(new String[]{"ls", "-l", "/some/directory"});

ProcessBuilder is more flexible and easier to manage, especially for complex commands.

 import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;

public class RunCommandWithBuilder {
    public static void main(String[] args) {
        try {
            // Build the command
            ProcessBuilder pb = new ProcessBuilder(Arrays.asList("ls", "-l"));

            // Optional: Set working directory
            // pb.directory(new File("/path/to/dir"));

            // Start the process
            Process process = pb.start();

            // Read output
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream())
            );

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // Wait and get exit code
            int exitCode = process.waitFor();
            System.out.println("Exit code: " exitCode);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Advantages of ProcessBuilder :

  • Better handling of command arguments.
  • Easy to set environment variables: pb.environment().put("VAR", "value") .
  • Can set working directory with pb.directory(new File("/path")) .
  • Cleaner syntax for complex commands.

Handling Errors and Input

Commands may produce error output, so it's good practice to read both stdout and stderr:

 BufferedReader errorReader = new BufferedReader(
    new InputStreamReader(process.getErrorStream())
);
String errorLine;
while ((errorLine = errorReader.readLine()) != null) {
    System.err.println(errorLine);
}

If your command requires input (eg, interactive scripts), write to the process's output stream:

 try (BufferedWriter writer = new BufferedWriter(
     new OutputStreamWriter(process.getOutputStream()))) {
    writer.write("yes");
    writer.newLine();
    writer.flush();
}

Security and Best Practices

  • Avoid injecting user input directly into commands (risk of command injection).
  • Prefer ProcessBuilder for better control.
  • Always handle exceptions and close streams properly.
  • Be aware that commands are OS-dependent (eg, dir vs ls ).

Basically, use ProcessBuilder for new code — it's clearer, safer, and more maintainable. Just remember to handle output, errors, and platform differences.

以上是如何從Java運行命令行命令的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

PHP教程
1535
276
Excel查找並更換不工作 Excel查找並更換不工作 Aug 13, 2025 pm 04:49 PM

checkSearchSettingStingsTike“ matchentirecellcontents”和“ matchcase” byexpandingOptionsInfindReplace,確保“ lookin” insettovaluesand and“ tocorrectscope; 2.2.look forhiddenChindChareChideCharacterSorformattingTingtingTingTingBycopypopyBycopyingByingTextDextDirectly

如何在Java應用程序中配置記錄? 如何在Java應用程序中配置記錄? Aug 15, 2025 am 11:50 AM

使用SLF4J結合Logback或Log4j2是Java應用中配置日誌的推薦方式,通過添加對應Maven依賴引入API和實現庫;2.在代碼中通過SLF4J的LoggerFactory獲取日誌記錄器,使用參數化日誌記錄方法編寫解耦且高效的日誌代碼;3.通過logback.xml或log4j2.xml配置文件定義日誌輸出格式、級別、目標(控制台、文件)及包級別的日誌控制;4.可選啟用配置文件掃描功能實現日誌級別的動態調整,SpringBoot中還可通過Actuator端點管理;5.遵循最佳實踐,包括

如何部署Java應用程序 如何部署Java應用程序 Aug 17, 2025 am 12:56 AM

PrepareyourapplicationbyusingMavenorGradletobuildaJARorWARfile,externalizingconfiguration.2.Chooseadeploymentenvironment:runonbaremetal/VMwithjava-jarandsystemd,deployWARonTomcat,containerizewithDocker,orusecloudplatformslikeHeroku.3.Optionally,setup

XML數據與Java中的蓖麻結合 XML數據與Java中的蓖麻結合 Aug 15, 2025 am 03:43 AM

CastorenablesXML-to-Javaobjectmappingviadefaultconventionsorexplicitmappingfiles;1)DefineJavaclasseswithgetters/setters;2)UseUnmarshallertoconvertXMLtoobjects;3)UseMarshallertoserializeobjectsbacktoXML;4)Forcomplexcases,configurefieldmappingsinmappin

js添加元素到數組的開始 js添加元素到數組的開始 Aug 14, 2025 am 11:51 AM

在JavaScript中,向數組開頭添加元素最常用的方法是使用unshift()方法;1.使用unshift()會直接修改原數組,可添加一個或多個元素,返回添加後的數組新長度;2.若不想修改原數組,推薦使用擴展運算符(如[newElement,...arr])創建新數組;3.也可使用concat()方法,將新元素數組與原數組合併,返回新數組且不改變原數組;綜上,修改原數組時用unshift(),保持原數組不變時推薦擴展運算符。

績效比較:Java vs.去後端服務 績效比較:Java vs.去後端服務 Aug 14, 2025 pm 03:32 PM

GoTypeDeptersbetterruntimePerformanceWithHigherThrougherTuptuptudandlaterLatency,尤其是Fori/O-HevyServices,DuetoItslightWeightGoroutGoroutineSandefficientsCheduler,wherjava,whilejava,themlowertostart,bylowertostart,themlowertostart,canmatchgoincpuindtaskspu-boundtasksafterjitoptoptimization.2.gous.2.gous.2.gous.2.gous.2.gous.2.2.gome

如何在Java與JSON合作 如何在Java與JSON合作 Aug 14, 2025 pm 03:40 PM

Toworkwithjsoninjava,Usephird-Partylybrarylikejackson,Gson,Orjson-B,Asjavalacksbuilt-Insupport; 2.Fordeserialization,MapjSontojavaObjectsosiboseobjectsoblectsosivessobectssoblectmmapperinjacperinjacperinjacperinjacperinjacperinorgon.fromjson.fromjson; 3.forserialialial;

Java中的斷言關鍵字是什麼? Java中的斷言關鍵字是什麼? Aug 17, 2025 am 12:52 AM

TheassertkeywordinJavaisusedtovalidateassumptionsduringdevelopment,throwinganAssertionErroriftheconditionisfalse.2.Ithastwoforms:assertcondition;andassertcondition:message;withthelatterprovidingacustomerrormessage.3.Assertionsaredisabledbydefaultandm

See all articles