0
我試圖做到這一點運行腳本管道與Java
echo "ls|head -3"|/bin/sh
在Java中
。
重要的一點是,我想立即創建腳本字符串並使用該腳本運行shell進程並捕獲腳本stdout。
上面的代碼不工作並掛起,可能在輸入流。
Process p = Runtime.getRuntime().exec("/bin/sh");
final OutputStream out = p.getOutputStream();
final BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
final String cmd = "ls|head -3";
new Thread(new Runnable() {
@Override
public void run() {
try {
out.write(cmd.getBytes());
out.flush();
} catch (IOException ex) {
}
}
}).start();
final List list = new ArrayList();
new Thread(new Runnable() {
@Override
public void run() {
try {
String line;
while ((line = in.readLine()) != null) {
list.add(line);
}
} catch (IOException ex) {
}
}
}).start();
System.err.println("running ...");
p.waitFor();
System.err.println(list);
}
而是讀利用現有> 0在您的測試讀取條件 – twillouer