sihi
sihi

Reputation: 15

How do I redirect from console (including error and output) to a file in Java?

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

When I run this code, I get the output of this code printed to the console. However, I wasn't able to figure out how to copy that output to a file. How would I go about doing so?

Upvotes: 1

Views: 804

Answers (2)

MihaiC
MihaiC

Reputation: 1583

A more simple solution is to change the outputstream of System.out to a file. This way, every time you invoke System.out.println(...) it will write to said file. Add this to the start of your program:

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

You can do the same for System.err for printing errors to a different file.

Upvotes: 0

fge
fge

Reputation: 121860

Use a 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

Read the javadoc carefully; there is a lot more you can do with it (affecting the environment, changing the working directory etc).

Also, do you really need to go through an interpreter at all?

Upvotes: 4

Related Questions