springboot中如何运行linux命令呢?

戚薇 SpringBoot 发布时间:2023-06-07 22:10:41 阅读数:8781 1
下文笔者讲述SpringBoot中运行Linux命令的方法及示例分享,如下所示
使用Java中的Runtime类或ProcessBuilder类
     即可运行Linux命令
例:

使用Runtime类-运行Linux命令

@RestController
public class MyController {
    
    @GetMapping("/execCommand")
    public String execCommand() {
        String command = "ls -l /tmp"; //待运行的Linux命令
        try {
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec(command);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder stringBuilder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
                stringBuilder.append(System.getProperty("line.separator"));
            }
            return stringBuilder.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "Error";
        }
    }
}

使用ProcessBuilder类--运行linux命令

@RestController
public class MyController {
    
    @GetMapping("/execCommand")
    public String execCommand() {
        String command = "ls -l /tmp"; //待运行的Linux命令
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(command.split(" "));
            Process process = processBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder stringBuilder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
                stringBuilder.append(System.getProperty("line.separator"));
            }
            return stringBuilder.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "Error";
        }
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/SpringBoot/202306/6742.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者