《java代码记录》-使用java运行服务器上的.sh文件

阿丹:
        记录一下使用java来运行服务器上的sh脚本。

import java.io.IOException;

public class RunShellScript {

    public static void main(String[] args) {
        String scriptPath = "/path/to/your/script.sh"; // 替换为你的Shell脚本路径
        try {
            // 使用Runtime.exec方法执行Shell脚本
            Process process = Runtime.getRuntime().exec(new String[]{"bash", scriptPath});

            // 等待脚本执行完成
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                System.out.println("Shell script executed successfully.");
            } else {
                System.err.println("Error executing shell script. Exit code: " + exitCode);
            }

            // 关闭进程的输入流、输出流和错误流,防止资源泄露
            process.getErrorStream().close();
            process.getInputStream().close();
            process.getOutputStream().close();

        } catch (IOException e) {
            System.err.println("Error executing the command: " + e.getMessage());
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("Process was interrupted: " + e.getMessage());
        }
    }
}

你可能感兴趣的:(开发使用工具类,java,服务器,开发语言)