This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
The PrintWriter(File file) constructor is provided as a shortcut to save you having to create you own FileWriter. The PrintWriter(Writer writer) constructor can be used to pass in any type of Writer and so can be used where you don't know/care what type of Writer you will be writing to. Generally speaking, if you are creating the PrintWriter to write to a file and have a File object (or file name) then use the PrintWriter(File file) constructor otherwise use the PrintWriter(Writer writer) constructor.
You will see this pattern where Writers/Readers are constructed using other Writer/Readers all over the java.io package. This is called a Decorator pattern. It allows you to mix and match functionality as you see fit. So, for example, if you want to print to a file you can do this
If you want to write to a Pipe you do this
If you want to use bufferring before writing to a file you do
If they didn't have a decorator pattern, they would had to implement lot of classes that have all these combinations
Nakul P. Patel
Joined: May 31, 2011
@ Tony Docherty:"The PrintWriter(Writer writer) constructor can be used to pass in any type of Writer and so can be used where you don't know/care what type of Writer you will be writing to."
Can you please tell me what are different types of Writer in java.io package?
If possible please write small line of code,it will help me(us) to understand in better way.