JAVA 执行 Linux 命令

引言

在开发过程中,我们经常需要通过代码执行一些系统命令,例如在Linux系统中执行一些常用的操作,如创建文件、移动文件、查看文件夹等。对于Java开发者来说,使用Java来执行Linux命令是一种常见的需求。

本文将介绍如何在Java中执行Linux命令,并提供一些示例代码来帮助读者更好地理解。

Java中执行Linux命令的方式

Java提供了多种方式来执行Linux命令,以下是其中几种常见的方式:

  1. 使用Runtime.getRuntime().exec()方法
  2. 使用ProcessBuilder
  3. 使用第三方库,如Apache Commons Exec

下面将详细介绍每种方式的使用方法。

1. 使用Runtime.getRuntime().exec()方法

Runtime.getRuntime().exec()方法可以直接在Java代码中运行一个外部命令。以下是一个示例代码:

public class ExecuteCommandExample {
    public static void main(String[] args) {
        try {
            // 执行命令
            Process process = Runtime.getRuntime().exec("ls -l");

            // 获取命令输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 等待命令执行完毕
            int exitCode = process.waitFor();
            System.out.println("命令执行完毕,退出码:" + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

上述代码中,我们使用Runtime.getRuntime().exec("ls -l")执行了一个ls -l命令,然后通过BufferedReader来读取命令输出,最后输出命令执行的退出码。

这种方式需要注意的是,命令执行可能会产生大量输出,如果不及时读取输出,可能会导致阻塞。

2. 使用ProcessBuilder

ProcessBuilder类提供了更高级的方式来执行外部命令,并且可以更好地控制命令的输入和输出。以下是一个示例代码:

public class ExecuteCommandExample {
    public static void main(String[] args) {
        try {
            // 构建命令
            ProcessBuilder builder = new ProcessBuilder("ls", "-l");

            // 启动进程并等待命令执行完毕
            Process process = builder.start();
            int exitCode = process.waitFor();

            // 获取命令输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            System.out.println("命令执行完毕,退出码:" + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

上述代码中,我们使用ProcessBuilder构建了一个ls -l命令,并通过start()方法启动进程,然后通过BufferedReader来读取命令输出,最后输出命令执行的退出码。

使用ProcessBuilder可以更灵活地设置命令的一些参数,例如工作目录、环境变量等,具体可以参考Java官方文档。

3. 使用Apache Commons Exec

Apache Commons Exec是一个开源的Java库,提供了更高级的方式来执行外部命令,并且具有更好的跨平台性能。以下是一个示例代码:

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.ExecuteResultHandler;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.Executor;
import org.apache.commons.exec.PumpStreamHandler;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class ExecuteCommandExample {
    public static void main(String[] args) {
        try {
            // 构建命令
            CommandLine commandLine = new CommandLine("ls");
            commandLine.addArgument("-l");

            // 创建Executor
            Executor executor = new DefaultExecutor();

            // 设置命令超时时间
            ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
            executor.setWatchdog(watchdog);

            // 设置命令输出
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
            executor.setStreamHandler(streamHandler);

            // 执行命令
            executor.execute