感谢我吧,什么都不说,直接上代码:
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,这个自动帮你输入了。代码要改改。
Original: https://www.cnblogs.com/yuluoxingkong/p/16115526.html
Author: yuluoxingkong
Title: java执行shell脚本怎么进行交互处理
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/529679/
转载文章受原作者版权保护。转载请注明原作者出处!