如何從Java運行命令行命令
使用Runtime.exec()可執行外部命令,但需用字符串數組避免空格問題;2. 推薦使用ProcessBuilder,因其更靈活,可設置環境變量、工作目錄且語法清晰;3. 應同時讀取stdout和stderr並處理輸入輸出流;4. 避免命令注入,妥善處理異常和流關閉;5. 注意命令的平台依賴性,新代碼應優先使用ProcessBuilder以確保安全性和可維護性。
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"});
Using ProcessBuilder
(Recommended)
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
vsls
).
Basically, use ProcessBuilder
for new code — it's clearer, safer, and more maintainable. Just remember to handle output, errors, and platform differences.
以上是如何從Java運行命令行命令的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

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

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

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

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

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

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

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

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

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

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

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

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