0

I have already looked into several SFO Links e.g. for a solution. What I have is code written by my colleague which has around 30 methods, and involves nested loops. The problem with this is when I try to run the code in eclipse, the console output has the long-tail issue.

What I was looking in was to print the results (intermediate results) on the console as well as on to a file (without making changes to all the sysout commands within all methods).

What I have done now is something like this

PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);

But this only write to a file and not on the display.

Betafish
  • 1,212
  • 3
  • 20
  • 45
  • Well, you should check if there is a default `OutputStream` that duplicate the output (never checked) or you can write you own class that will write into multiple `OutputSteam` (one inherited, the rest in a `Collection`), then set that instance in `System.out` – AxelH Nov 20 '17 at 07:52
  • 2
    Is this specifically about Eclipse? There is a setting in Eclipse to write all output to a file as well as console - Run Configurations > configuration for what you're running > Common > check Output File and select location. – Jiri Tousek Nov 20 '17 at 07:55

3 Answers3

1

You could branch your output stream using TeeOutputStream to print to both console and a text file

T A
  • 1,677
  • 4
  • 21
  • 29
1

Extending PrintStream is comparatively easy. Try something like:

class ForkOut extends PrintStream {
    // The other stream to write to.
    final PrintStream[] others;

    public ForkOut(PrintStream o1, PrintStream... others) {
        super(o1);
        this.others = others;
    }

    @Override
    public void write(int b) {
        super.write(b);
        // Echo every write to the other streams.
        for ( PrintStream o : others ) {
            o.write(b);
        }
    }

    @Override
    public void write(byte[] buf, int off, int len) {
        super.write(buf, off, len);
        // Echo every write to the other streams.
        for ( PrintStream o : others ) {
            o.write(buf, off, len);
        }
    }
}

public void test(String[] args) throws FileNotFoundException {
    System.out.println("Hello");
    System.setOut(new ForkOut(System.out, new PrintStream(new FileOutputStream("output.txt"))));
    System.out.println("Hello again!");
}
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
0

The System.setOut() method redirects all outputs to the System.out Stream to the desired Stream(which in your case is the PrintStream out). You could consider writing the results into the file with the out.print(String) method and on the console with the System.out.print(String) method

Cels
  • 1,212
  • 18
  • 25