Output to text file, console empty - Java

Viewed 277
BufferedReader br = new BufferedReader(new FileReader("shark-data.txt"));
String fileRead = br.readLine();
PrintStream out = new PrintStream(new FileOutputStream("results.txt"));
System.setOut(out);

The code works, it creates a new text file and puts my output from the console into the text file. The problem is that nothing appears on my console. How do I fix this?

3 Answers

You could use TeeOutputStream from Apache commons-io to split the stream in two: https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/output/TeeOutputStream.html

OutputStream fos = new FileOutputStream("results.txt");
OutputStream consoleOut = System.out;
PrintStream newOut = new PrintStream(new TeeOutputStream(consoleOut, fos));
System.setOut(newOut);

This will create a PrintStream writing to both the original System.out (i.e. to the console) and to your file.

In Maven, here is the dependency snippet which you could use to add commons-io to you project:

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.6</version>
    </dependency>

First you have to create a class where you inherit from OutputStream interface to implement the adapter pattern ( I m not yet sure if is adapter )

then you can use this class as bellow

MAIN

        PrintStream finalStream;
        TreeOutputStream tos;
        PrintStream out;

        out = new PrintStream("logs.txt");

        tos = new TreeOutputStream();
        tos.add(out);
        tos.add(System.out);
        finalStream = new PrintStream(tos);
        System.setOut(finalStream);

TreeOutputStream

public class TreeOutputStream extends OutputStream{

private final List<OutputStream> streams;

public void add(OutputStream os){
    streams.add(os);
}

public void remove(OutputStream os){
    streams.remove(os);
}

public TreeOutputStream() {
    streams = new ArrayList<>();
}

@Override
public void write(int i) throws IOException {
    streams.stream().forEach(strm->{
        try {
            strm.write(i);
        } catch (IOException ex) {
            Logger.getLogger(TreeOutputStream.class.getName()).log(Level.SEVERE, null, ex);
        }
    });
}

}

what happens that your out stream will loop over all streams calling their write method

Before executing System.setOut save standart console,

PrintStream standard = System.out;

to print to console again you should switch to standart console using below, than You can ptint to console.

System.setOut(standard); System.out.println("Hello!");

Related