Formatted output to file and console

The essence of the question:
In theory, you need to create a module that will write output streams to the console and to the file in the form :

In my case i.e.:

  • 0: Compute 1/2 ... ; result: 0
  • 1: Something goes wrong
  • 2: Done computing

I seem to understand conceptually about what needs to be done, but I got stuck with the implementation.

public class Main{
    public static void main(String[] args) throws Exception {
        System.out.print("Compute 1/2 ...");
        System.out.println(" ; result: " + (1 / 2));
        try {
            int a = 27 / 0;
        } catch (ArithmeticException err) {
            System.out.println("Something goes wrong");
        }
        System.out.println("Done computing");

        String directory = "D://Checknewfiles";
        String fileNameForLog = "log.txt";
        File file = new File(directory, fileNameForLog);
        file.createNewFile();

        System.setOut(new Logic(System.out));    
    }
}

class Logic extends PrintStream {

     public Logic(OutputStream out) {            //доделать
         super(out);                          
     }

     public void print(String s) {
         int count = 0;
         for (int i = 0; i < count; ++i) {
             count++;
             print(count +": " + s);
         }
     }
 }
Author: 0xdb, 2017-11-15

1 answers

I will assume that the variable count must be declared as a class field, so that its value is preserved between calls to the print method.

class Logic extends PrintStream {
    private PrintStream wrapper;
    private int count;

    public Logic(OutputStream out) {
        super(out);
        this.wrapper = new PrintStream(out);
    }

    @Override
    public void print(String s) {
        count++;
        wrapper.print(count + ": " + s);
    }
}
 2
Author: Victor Khovanskiy, 2017-11-15 18:38:34