Andre
Andre

Reputation: 7638

Java: How to print every output of the console either in the console and in a file?

Evening, I have this need:

Every output of the console should be printed into a file but also still in the console. and the /n should be changed with lineSeparator().

How can I achieve that?

Upvotes: 0

Views: 347

Answers (2)

mitesh7172
mitesh7172

Reputation: 696

You can print the output in output file by using FileOutputStream and PrintStream, You can try below code for better understanding.

import java.io.*;

public class ReadFile {
    public static void main(String[] args) throws FileNotFoundException {
        java.io.File outFile = new java.io.File ("File name" );
        FileOutputStream fos = new FileOutputStream(outFile);
        PrintStream ps = new PrintStream(fos);
        System.setOut(ps);
        for(int i = 0 ; i < 5 ; i++) {
            System.out.println(i);
        }
    }
}

This code prints the output in the text file, If the text file does not exist then it creates a new file and then prints output in the file.

Upvotes: 1

Usagi Miyamoto
Usagi Miyamoto

Reputation: 6289

You can assign a PrintStream to System.out with System.setOut().

Thus you have to implement a PrintStream that outputs its input to the old System.out and a file simultaneously. (Overriding the FilterOutputStream.write() method.)

Upvotes: 1

Related Questions