繁体   English   中英

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

[英]Can't get output from Runtime.exec()

我已经编写了一个代码来通过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();

由于使用了管道符号,所以我无法成功执行命令。根据我最后一个问题的讨论,我将变量包装在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读取输出来使用正确的方法。

当我使用{"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通常更容易,它具有一些不错的选项,包括重定向错误/ stdout和设置执行上下文目录...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM