无法从Runtime.exec()获取输出

时间:2014-06-27 07:08:01

标签: java shell

我编写了一个代码,通过Java在shell上执行命令:

 String filename="/home/abhijeet/sample.txt";

        Process contigcount_p;

        String command_to_count="grep  \">\" "+filename+" | wc -l";

        System.out.println("command for counting contigs "+command_to_count); 

        contigcount_p=Runtime.getRuntime().exec(command_to_count);


         contigcount_p.wait();

由于正在使用管道符号,所以我无法成功执行命令。根据last question的讨论,我将变量包装在shell中:

Runtime.getRuntime().exec(new String[]{"sh", "-c", "grep \">\" "+filename+" | wc -l"});

这对我有用,因为它在shell上执行命令,但是当我尝试使用缓冲读取器读取其输出时:

   BufferedReader reader = 
                    new BufferedReader(new InputStreamReader(contigcount_p.getInputStream())); 

   String line=" ";
   while((line=reader.readLine())!=null)
   {
       output.append(line+"\n");
   }

它返回一个空值,我已经找到了一个临时解决方案,正如我在上一个问题上所讨论的那样:link,但我想通过使用BufferedReader读取它的输出来正确地使用它。< / p>

1 个答案:

答案 0 :(得分:0)

当我使用{"sh", "-c", "grep \">\" "+filename+" | wc -l"}的命令行时,它会一直覆盖我的文件

我必须更改它,以便引用双引号,{"sh", "-c", "grep \"\">\"\" "+filename+" | wc -l"}

所以,使用它作为我的测试文件的内容......

>
>
>

Not a new line >

并使用此代码......

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class TestProcess {

    public static void main(String[] args) {
        String filename = "test.tx";
        String test = "grep \"\">\"\" "+filename+" | wc -l";
        System.out.println(test);

        try {
            ProcessBuilder pb = new ProcessBuilder("sh", "-c", test);
            pb.redirectError();
            Process p = pb.start();
            new Thread(new Consumer(p.getInputStream())).start();

            int ec = p.waitFor();
            System.out.println("ec: " + ec);
        } catch (IOException | InterruptedException exp) {
            exp.printStackTrace();
        }
    }

    public static class Consumer implements Runnable {

        private InputStream is;

        public Consumer(InputStream is) {
            this.is = is;
        }

        @Override
        public void run() {
            try (BufferedReader reader =  new BufferedReader(new InputStreamReader(is))){
                String value = null;
                while ((value = reader.readLine()) != null) {
                    System.out.println(value);
                }
            } catch (IOException exp) {
                exp.printStackTrace();
            }
        }

    }

}

我能够产生这个输出......

grep "">"" test.tx | wc -l
4
ec: 0

通常,在处理外部进程时,通常更容易使用ProcessBuilder,它有一些不错的选项,包括重定向error / stdout和设置执行上下文目录......