Java runtime.getruntime()没有输出

时间:2014-12-27 02:15:29

标签: java

我正在尝试将curl命令作为Process by Java执行。当我执行它时,我根本没有得到任何输出。当我通过命令行执行相同的命令时,我得到了正确的输出。 URL将输出作为XML返回。

这是我的Java程序的代码。

public static void exec(){
        try {
            Process p = Runtime.getRuntime().exec(new String[]{"curl", "http://genome.ucsc.edu/cgi-bin/das/mm9/dna\\?segment\\=chr1:3206424,3206499"});
            BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line=null;
            while((line=input.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

这是我通过命令行执行的命令

curl http://genome.ucsc.edu/cgi-bin/das/mm9/dna\?segment\=chr1:3206424,3206499

当我使用以下字符串数组{"ls", "-al"}运行Java程序时,它为我提供了预期的输出

我将不胜感激。

1 个答案:

答案 0 :(得分:1)

您不等待Process完成。此外,您可以使用ProcessBuilderinheritIO()之类的

ProcessBuilder pb = new ProcessBuilder("curl",
        "http://genome.ucsc.edu/cgi-bin/das/mm9/dna?"
        + "segment=chr1:3206424,3206499");
pb.inheritIO();
try {
    Process p = pb.start();
    p.waitFor();
} catch (Exception e) {
    e.printStackTrace();
}

修改

从下面的评论中,您需要另一个Thread。像,

static class InputStreamReaderRunnable implements Runnable {
    private StringBuilder sb;
    private InputStream is;

    public InputStreamReaderRunnable(InputStream is) {
        this.is = is;
        this.sb = new StringBuilder();
    }

    @Override
    public void run() {
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line;
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line).append(System.lineSeparator());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String toString() {
        return sb.toString();
    }
}

public static void main(String[] args) {
    ProcessBuilder pb = new ProcessBuilder("curl",
            "http://genome.ucsc.edu/cgi-bin/das/mm9/dna?segment=chr1:3206424,3206499");
    try {
        Process p = pb.start();
        InputStreamReaderRunnable isrr = new InputStreamReaderRunnable(
                p.getInputStream());
        Thread t = new Thread(isrr);
        t.start();
        p.waitFor();
        t.join();
        String out = isrr.toString();
        System.out.println(out);
    } catch (Exception e) {
        e.printStackTrace();
    }
}