0

Can I use a PrintStream's println() method without involving the System class?

Tim Post
  • 33,371
  • 15
  • 110
  • 174
  • (a) Your actual question has nothing to do with your title. Which question do you want answered? (b) Did you consider *trying* it? – user207421 Mar 10 '12 at 08:54

2 Answers2

5

Absolutely - System.out and System.err are just the PrintStream values associated with standard out and standard error.

You can create a PrintStream from any OutputStream, or just by giving a filename. However, it will always use the system default encoding.

Prefer PrintWriter, which will wrap an arbitrary Writer. However, this will still suppress IOException from being thrown, which doesn't seem a good idea to me.

Prefer BufferedWriter:

BufferedWriter wrapper = new BufferedWriter(writer);
try {
    wrapper.write(...);
    wrapper.newLine();
} finally {
    wrapper.close();
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

The System class doesn't "reference the PrintStream class". It has two static fields of type PrintStream: out and err. So if you want to write to the out stream, you use System.out. If you want to write to the err stream, you use System.err. If you want to write to another PrintStream, you construct one by yourself: new PrintStream(...).

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • -1. Make up your mind. Either it doesn't reference the PrintStream class *or* it has two static variables of that type. You can't have it both ways. – user207421 Mar 10 '12 at 08:55
  • "Referencing a class" doesn't mean anything. Having a static field of a given type means something. – JB Nizet Mar 10 '12 at 09:04
  • References to other classes are what the class loader resolves when it loads a class. I don't find this meaningless in the slightest. – user207421 Mar 11 '12 at 09:06