import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * 获取脚本工具类 * * @author l_coil * @date 2021-1-13 */ @Slf4j public class ExecuteScriptUtils { public static void main(String[] args) { String a = execute(new String[]{"bash","cd ../"}); System.out.println(a); } /** * 执行脚本 * * @return String */ public static String execute(String instruction) { BufferedReader br = null; StringBuilder builder = new StringBuilder(); try { Process p = Runtime.getRuntime().exec(instruction); br = new BufferedReader(new InputStreamReader(p.getInputStream())); String readLine = br.readLine(); while (readLine != null) { readLine = br.readLine(); builder.append(readLine == null ? "" : readLine); } log.info("readLine" + readLine); p.waitFor(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return builder.toString(); } /** * 执行脚本 * * @return String */ public static String execute(String[] instruction) { BufferedReader br = null; StringBuilder builder = new StringBuilder(); try { ProcessBuilder processBuilder = new ProcessBuilder(instruction); // processBuilder.redirectErrorStream(true); Process p = processBuilder.start(); br = new BufferedReader(new InputStreamReader(p.getInputStream())); String str; while ((str = br.readLine())!=null) { builder.append(str); } p.waitFor(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return builder.toString(); } }
相关文章
- 12-132.8 补充:shell脚本执行方法
- 12-13libcurl 工具类
- 12-13工具类-Date
- 12-13Jmeter 命令执行脚本并输出报告
- 12-13如何用jshell执行java脚本?
- 12-13hutool的时间工具类
- 12-13时间工具类
- 12-13时间、日期工具类 DateUtil
- 12-13Android工具类篇 日期工具类【DateUtil】
- 12-13XML文件读取工具类