Home arrow static arrow Java Programming [Archive] - PrintWriter BufferedWriter JspWriter FileWriter- HELP!
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - PrintWriter BufferedWriter JspWriter FileWriter- HELP!
This topic has 3 replies on 1 page.

Posts:80
Registered: 12/7/98
PrintWriter BufferedWriter JspWriter FileWriter- HELP!  
Aug 1, 2004 4:36 PM



 
Help!

I am confused. So many Writers!

I wonder if someone can recommend an elegant solution.

I am writing some utility classes that write to output. This output could conceivable be
a) a web page (thru JspWriter)
b) a file (thru FileWriter I guess)
and it needs to be able to write to either of them.

Writer is a superclass of both JspWriter and FileWriter... but it doesnt have those nice println() functions. How should I approach this ?

public class MyUtils {
public static void doSomething(Writer / PrintWriter / BufferedWriter w) {
w.prinln("hello");
}
}

JspWriter out;
out.doSomething(out);

FileWriter fw = new FileWriter(new File("filename"));
fw.doSomething(fw);

thanks!
 

Posts:12,831
Registered: 2/22/00
Re: PrintWriter BufferedWriter JspWriter FileWriter- HELP!  
Aug 1, 2004 5:03 PM (reply 1 of 3)



 
Couldn't your method take a Writer as an argument, and then it creates a PrintWriter, using that Writer as an argument to the PrintWriter constructor?

That way you'd get the PrintWriter functionality, and the only thing in the argument is Writer, which is higher-level (as opposed to JspWriter, FileWriter, etc.).
 

Posts:80
Registered: 12/7/98
Re: PrintWriter BufferedWriter JspWriter FileWriter- HELP!  
Aug 2, 2004 2:40 AM (reply 2 of 3)



 
So, I can pass in a printwriter like this:

public class MyUtils {
public static void doSomething(PrintWriter w) {
w.println("hello");
}
}

JspWriter out;
out.doSomething(new PrintWriter(out, true));

FileWriter fw = new FileWriter(new File("filename"));
fw.doSomething(new PrintWriter(fw, true));

Like that ? (with autoflush=true)

So I guess I dont need bufferedwriter then...

THANKS!
 

Posts:12,831
Registered: 2/22/00
Re: PrintWriter BufferedWriter JspWriter FileWriter- HELP!  
Aug 2, 2004 4:46 AM (reply 3 of 3)



 
No, I meant something more like:
public void doSomething(Writer w) {    PrintWriter pw = new PrintWriter(w);    pw.println("Keplah!");    //etc}// later on, in some other class...FileWriter fw = new FileWriter("out.txt");otherThing.doSomething(fw);// and later again...JspWriter jspw = howeverYouGetAJspWriter();otherThing.doSomething(jspw);

etc.
 
This topic has 3 replies on 1 page.