温馨提示×

java如何执行linux脚本

小亿
81
2024-11-30 08:54:33
栏目: 编程语言

在Java中执行Linux脚本,你可以使用Runtime类或ProcessBuilder类。这里有两个示例:

示例1:使用Runtime类

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

public class ExecuteLinuxScript {
    public static void main(String[] args) {
        try {
            String scriptPath = "/path/to/your/script.sh";
            Process process = Runtime.getRuntime().exec("bash " + scriptPath);

            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("Exit code: " + exitCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

示例2:使用ProcessBuilder类

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

public class ExecuteLinuxScript {
    public static void main(String[] args) {
        try {
            String scriptPath = "/path/to/your/script.sh";
            ProcessBuilder processBuilder = new ProcessBuilder("bash", scriptPath);
            processBuilder.redirectErrorStream(true);

            Process process = processBuilder.start();

            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("Exit code: " + exitCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在这两个示例中,我们分别使用Runtime.getRuntime().exec()ProcessBuilder类来执行Linux脚本。请注意,你需要将/path/to/your/script.sh替换为你要执行的脚本的实际路径。这两个示例都会读取脚本的输出并将其打印到控制台。最后,我们还获取并打印了脚本的退出代码。

0