需要建议如何在Java中实现管道。例如,
echo "test"|wc
我需要显示上述管道示例的结果。
我试过这个:
public class myRunner {
private static final String[] cmd = new String[] {"wc"};
public static void main(String[] args){
try {
ProcessBuilder pb = new ProcessBuilder( cmd );
pb.redirectErrorStream(true);
Process process = pb.start();
OutputStream os = process.getOutputStream();
os.write("echo test".getBytes() );
os.close();
}catch (IOException e){
e.printStackTrace();
}
如何查看wc
输出的输出?
我相信我可以使用的另一个库是PipedInputStream
/ PipedOutputStream
。谁能展示一个如何使用它的例子?我很困惑。感谢
答案 0 :(得分:1)
如何查看wc输出的输出?
通过使用Process's
输出,通过Process.getInputStream()
并从中读取。
答案 1 :(得分:0)
public ArrayList<String> executorPiped(String[] cmd, String outputOld){
String s=null;
ArrayList<String> out=new ArrayList<String>();
try {
ProcessBuilder pb = new ProcessBuilder( cmd );
pb.redirectErrorStream(true);
Process p = pb.start();
OutputStream os = p.getOutputStream();
os.write(outputOld.getBytes());
os.close();
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
while ((s = stdInput.readLine()) != null) {
out.add(s);
}
}catch (IOException io){
}
return out;
}