如何从控制台(包括错误和输出)重定向到Java中的文件?

时间:2014-11-28 06:48:36

标签: java eclipse

package online_test;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class cmdline_test {
    /**
     * @param args
     */
    public static void main(String[] args) {
              try {
                    String[] command = new String[3];
                    command[0] = "cmd";
                    command[1] = "/c";
                    command[2] = "c: && dir && cd snap";

                    Process p = Runtime.getRuntime().exec(command);

                    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
                    String line = reader.readLine();
                    while (line != null) {
                        System.out.println(line);
                        line = reader.readLine();
                    }
                    BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
                    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                    String Error;
                    while ((Error = stdError.readLine()) != null) {
                        System.out.println(Error);
                    }
                    while ((Error = stdInput.readLine()) != null) {
                        System.out.println(Error);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

当我运行此代码时,我将此代码的输出打印到控制台。但是,我无法弄清楚如何将该输出复制到文件中。我该怎么做?

2 个答案:

答案 0 :(得分:4)

使用ProcessBuilder

final File outputFile = Paths.get("somefile.txt").toFile();
final ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "whatever")
    .redirectOutput(outputFile)
    .redirectErrorStream(true);

final Process p = pb.start();
// etc

仔细阅读javadoc;你可以用它做很多事情(影响环境,改变工作目录等)。

另外,你真的需要经过翻译吗?

答案 1 :(得分:0)

更简单的解决方案是将System.out的输出流更改为文件。这样,每次调用System.out.println(...)时,它都会写入所述文件。将其添加到程序的开头:

    File file =
        new File("somefile.log");
    PrintStream printStream = null;
    try {
        printStream = new PrintStream(new FileOutputStream(file));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    System.setOut(printStream);

您可以对System.err执行相同操作,以便将错误打印到其他文件。