感謝我吧,什么都不說,直接上代碼:
package utils; import java.io.*; public class ShellUtils { public static String convertStreamToStr(InputStream is) throws IOException { InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } return sb.toString(); } public static String run(String cmd) { String res = null; try { Process process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", cmd}, null, null); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream())); String line; while ((line = reader.readLine()) != null){ writer.write("aaaaa"); writer.newLine(); writer.flush(); res = convertStreamToStr(process.getInputStream()); } } catch (IOException e) { e.printStackTrace(); } return res; } }

#a.sh echo "正在安裝" read -p "是否進行: > " choice echo $choice
import cn.hutool.core.io.FileUtil; import utils.ShellUtils; import java.io.File; public class Main { public static void main(String[] args) { File file = new File("script/a.sh"); String s = FileUtil.readUtf8String(file); String run = ShellUtils.run("/Users/happysmile/Documents/code/demo/script/a.sh"); System.out.println("run:" + run); } }
測試
```java package utils; import java.io.*; public class ShellUtils { public static String convertStreamToStr(InputStream is) throws IOException { InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } return sb.toString(); } public static String run(String cmd) { String res = null; try { Process process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", cmd}, null, null); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream())); writer.write("y");//相當於代替你輸入了一次y writer.newLine();//相當於代替你敲了一次回車 writer.flush();//把數據刷新進內存,相當於使之生效 res = convertStreamToStr(process.getInputStream()); } catch (IOException e) { e.printStackTrace(); } return res; } }
下面說原理。
就是在拿到那個輸出前再多給它輸入一些東西嘛,
比如有個腳本非得輸入y才可以執行下去,你用java執行這些腳本總不能手動去輸入吧。ok,這個自動幫你輸入了。代碼要改改。
