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

查看:34
本文介绍了使用 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?

推荐答案

Runtime.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天全站免登陆