javajava.util.scannersystem.outsystem.in

What is the analogue for Scanner/System.in if I want to do the output?


If I use the Scanner type for reading System.out, I can easily switch from System.in to some file and thus I can test the methods working with the input.

    String line;

       Scanner in = new Scanner(System.in);  // reading from the command line
    
    // or
 
       File file = new File(someFileName);   
       in = new Scanner(file);              // reading from the file

    System.out.print("Type something: ");
    line = in.nextLine();
    System.out.println("You said: " + line);

But what type can I use for the same switch for the output, if I want my methods to alternatively write to a file or to System.out?


Solution

  • System.out is a PrintStream. You can always create your own PrintStream that writes to a file.

    PrintStream out = System.out;
    out.print("Write to console");
    out = new PrintStream(new File("path"));
    out.print("Write to file");
    

    Just be careful.System.out shouldn't be closed while a PrintStream created from a file should be closed.