0

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?

Gangnus
  • 24,044
  • 16
  • 90
  • 149

1 Answers1

2

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.

magicmn
  • 1,787
  • 7
  • 15