在Java中執行Linux命令有以下幾種方法:
String command = "ls -a";
Process process = Runtime.getRuntime().exec(command);
// 獲取命令執行的輸出結果
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// 等待命令執行完成
int exitCode = process.waitFor();
System.out.println("Exit code: " + exitCode);
List<String> command = Arrays.asList("ls", "-a");
ProcessBuilder processBuilder = new ProcessBuilder(command);
// 設置工作目錄
processBuilder.directory(new File("/path/to/directory"));
// 執行命令
Process process = processBuilder.start();
// 獲取命令執行的輸出結果,等待命令執行完成
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int exitCode = process.waitFor();
System.out.println("Exit code: " + exitCode);
首先需要在項目中引入Apache Commons Exec庫的依賴,然后可以使用CommandLine對象來執行命令。
CommandLine commandLine = new CommandLine("ls");
commandLine.addArgument("-a");
DefaultExecutor executor = new DefaultExecutor();
// 設置工作目錄
executor.setWorkingDirectory(new File("/path/to/directory"));
// 執行命令
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
executor.setStreamHandler(streamHandler);
int exitCode = executor.execute(commandLine);
System.out.println(outputStream.toString());
System.out.println("Exit code: " + exitCode);
以上是三種常用的方法,可以根據需要選擇適合的方法來執行Linux命令。