0

How to print logs, warnings other than console output in a file in java? I have tried this

import java.io.*;
 
public class SystemFact
{
    public static void main(String arr[]) throws FileNotFoundException
    {
        // Creating a File object that represents the disk file.
        PrintStream o = new PrintStream(new File("A.txt"));
 
        // Store current System.out before assigning a new value
        PrintStream console = System.out;
 
        // Assign o to output stream
        System.setOut(o);
        System.out.println("This will be written to the text file");
 
        // Use stored value for output stream
        System.setOut(console);
        System.out.println("This will be written on the console!");
    }
}

I didnt get the expected result

Priya
  • 13
  • 3
  • 1
    Maybe you need to flush the output? System.out.flush(); – Noixes May 31 '21 at 11:11
  • Does this answer your question? [System.out to a file in java](https://stackoverflow.com/questions/2851234/system-out-to-a-file-in-java) – Turamarth May 31 '21 at 11:11
  • 1
    *"How to print **logs**"* --- The keyword here is **log**, so don't use `System.out.print`, but use a **Logging** Library instead. That's what they are for. – Andreas May 31 '21 at 11:14
  • Also, there are libraries that handling logging for you such as Log4J and SLF4J. Doing Logging correctly is hard, don't try to implement it by yourself if you don't need to! – Nir Alfasi May 31 '21 at 11:15
  • 1
    To answer your direct question: Set auto-flush to true like this when creating the *PrintStream*: `new PrintStream(new FileOutputStream("file.txt"), true)` – Matt May 31 '21 at 11:17

0 Answers0