springboot中如何运行linux命令呢?
下文笔者讲述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"; } } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。