| Author |
Difference bet'n PrintWriter and FileWriter class.
|
Nakul P. Patel
Greenhorn
Joined: May 31, 2011
Posts: 23
|
|
I got confused when i tried following code.
try{
File file = new File("write.txt");
FileWriter writer = new FileWriter(file);
PrintWriter printWriter = new PrintWriter(writer);
printWriter.println("pqr");
printWriter.println("jkl");
printWriter.close();
PrintWriter printWriter = new PrintWriter(file);
printWriter.println("abc");
printWriter.println("xyz");
printWriter.close();
}
what is the basic Difference Between following PrintWriter(File file) and PrintWriter(FileWriter writer) need example to explain
and in what scenario i should use these classes
|
 |
Tony Docherty
Bartender
Joined: Aug 07, 2007
Posts: 1223
|
|
The PrintWriter(File file) constructor creates a PrintWriter object that writes to the specified file.
The PrintWriter(FileWriter writer) constructor doesn't exist but there is a PrintWriter(Writer writer) constructor which creates a PrintWriter object that writes to the specified Writer which in your code is a FileWriter.
and in what scenario i should use these classes
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.
|
 |
Jayesh A Lalwani
Bartender
Joined: Jan 17, 2008
Posts: 1321
|
|
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
Greenhorn
Joined: May 31, 2011
Posts: 23
|
|
Hi,
@ 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.
|
 |
Jayesh A Lalwani
Bartender
Joined: Jan 17, 2008
Posts: 1321
|
|
|
If you look at the Writer javadocs, it lists all the classes that implement the Writer interface
|
 |
 |
|
|
subject: Difference bet'n PrintWriter and FileWriter class.
|
|
|