无法从获得的Runtime.exec输出()(Can't get output from R

2019-10-20 08:32发布

我已经写了代码,通过Java外壳上执行命令:

 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();

由于管道符号都被使用,所以我没能按我的命令执行successfully.As 最后一个问题的讨论中,我都包裹着我的变量在外壳:

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");
   }

它返回一个空值,我已经为它找到一个临时解决方案,因为我已经在前面的问题讨论: 链接 ,但我想通过阅读它的使用的BufferedReader输出用做它的正确途径。

Answer 1:

当我使用的命令行{"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和设置执行上下文目录...



文章来源: Can't get output from Runtime.exec()
标签: java shell