我想在java中通过cmd执行git命令,并希望验证收到的整个输出。 预期:
克隆到' gitrepo' ...
remote:计算对象:92,完成
remote:查找来源:100%(92/92)
远程:获取尺寸:100%(76/76)
remote:压缩对象:98%(2370/2400)
远程:总计92(增量14),重用89(增量14)
解包对象:100%(92/92),已完成。
检查连接性......已完成。
尝试No.1 - ProcessBuilder
ProcessBuilder proc = new ProcessBuilder(commands);
proc. redirectErrorStream(true);
proc.redirectOutput();
final Process p = proc.start();//Runtime.getRuntime().exec(cur_string);
//Handle streams
//in
new Thread(new Runnable(){
public void run(){
Scanner stdin = new Scanner(p.getInputStream());
while(stdin.hasNextLine()){
System.out.println(stdin.nextLine());
if (stdin.nextLine().isEmpty())
break;
}
System.out.println("exit");
stdin.close();
}
}).start();
//wait
p.waitFor();
p.destroyForcibly();
结果:在循环中挂起
尝试第2号 - 新线程中的扫描仪
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
List<String> commands = new ArrayList<String>();
commands.add("cmd.exe");
commands.add("/k");
commands.add("cd D:/" + " && D: && git clone --depth 1 <url>");
ProcessBuilder pb = new ProcessBuilder(commands);
pb.redirectErrorStream(true);
try {
Process prs = pb.start();
Thread inThread = new Thread(new In(prs.getInputStream()));
inThread.start();
Thread.sleep(2000);
} catch (IOException e) {
e.printStackTrace();
}
}
class In implements Runnable {
private InputStream is;
public In(InputStream is) {
this.is = is;
}
@Override
public void run() {
byte[] b = new byte[1024];
int size = 0;
try {
while ((size = is.read(b)) != -1) {
System.out.println(new String(b));
}
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
结果 - 循环播放
尝试3号 - Runnable Class
final Process _p = Runtime.getRuntime().exec("cmd.exe /k cd \"D:\\" && D: && git clone --depth 1 <url>");
// Handle stdout...
new Thread() {
public void run() {
try {
Streams.copy(_p.getInputStream(), System.out,true);
} catch (Exception anExc) {
anExc.printStackTrace();
}
}
}.start();
// Handle stderr...
new Thread() {
public void run() {
try {
Streams.copy(_p.getInputStream(), System.out,true);
} catch (Exception anExc) {
anExc.printStackTrace();
}
}
}.start();
_p.waitFor();
结果 - 永不返回
尝试4号 - org.apache.commons.fileupload.utils.stream
String output = new ProcessExecutor().command("git", "clone","--depth","1","url")
.readOutput(true).directory(new File("D:/git")).execute()
.outputUTF8();
System.out.println(output);
结果 - 永久挂起
尝试第5号 - Crydust / Git.java
https://gist.github.com/Crydust/fd1b94afc52cd0f7dd4c
结果 - 仅返回第一个语句&#34;克隆到git.repo ...&#34;
尝试6号--apache.commomns.executor(执行者看门狗)
结果 - 挂起
尝试7号 - ztexec库
Value
0 0.5
1 0.8
2 -0.2
3 None
4 None
5 None
结果 - 仅返回第一个语句&#34;克隆到git.repo ...&#34;
注意:::不使用jgit库,因为需要浅克隆 jgit尚不支持。