使用System.setOut()重定向Runtime.getRuntime()。exec(); [英] Redirect Runtime.getRuntime().exec() output with System.setOut();

查看:121
本文介绍了使用System.setOut()重定向Runtime.getRuntime()。exec();的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序Test.java:

I have a program Test.java:

import java.io.*;

public class Test {
    public static void main(String[] args) throws Exception {
        System.setOut(new PrintStream(new FileOutputStream("test.txt")));
        System.out.println("HelloWorld1");
        Runtime.getRuntime().exec("echo HelloWorld2");
    }
}

这应该将HelloWorld1和HelloWorld2打印到文件中的text.txt。但是,当我查看文件时,我只看到HelloWorld1。

This is supposed to print HelloWorld1 and HelloWorld2 to the file text.txt. However, when I view the file, I only see HelloWorld1.


  1. HelloWorld2去了哪里?它消失了吗?

  1. Where did HelloWorld2 go? Did it vanish into thin air?

假设我想将HelloWorld2重定向到test.txt。我不能在命令中添加>> test.txt,因为我会得到一个文件已经打开错误。那我该怎么做呢?

Lets say I want to redirect HelloWorld2 to test.txt also. I can't just add a ">>test.txt" in the command because I'll get a file already open error. So how do I do this?


推荐答案

运行时的标准输出。 exec不会自动发送到调用者的标准输出。

The standard output of Runtime.exec is not automatically sent to the standard output of the caller.

这样的事情要做 - 获取分叉进程的标准输出,读取然后再读取把它写出来。请注意,使用Process实例的 getInputStream()方法,可以使用分叉进程的输出。

Something like this aught to do - get access to the standard output of the forked process, read it and then write it out. Note that the output from the forked process is availble to the parent using the getInputStream() method of the Process instance.

public static void main(String[] args) throws Exception {
    System.setOut(new PrintStream(new FileOutputStream("test.txt")));
    System.out.println("HelloWorld1");

     try {
       String line;
       Process p = Runtime.getRuntime().exec( "echo HelloWorld2" );

       BufferedReader in = new BufferedReader(
               new InputStreamReader(p.getInputStream()) );
       while ((line = in.readLine()) != null) {
         System.out.println(line);
       }
       in.close();
     }
     catch (Exception e) {
       // ...
     }
}

这篇关于使用System.setOut()重定向Runtime.getRuntime()。exec();的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆