First of all, don't reinitialize the PrintStream object in every loop iteration.
To write to a file, simply call PrintStream's println method. You may not realise it, but when you print to the console, this is exactly what you are doing. System.out is a PrintStream object.
PrintStream out =
new PrintStream(new File("stuff.txt"));
while (in.hasNext()) {
String word = in.next();
out.println(convert(word));
}
import java.io.PrintStream;
public class Main2{
public static void main(String[]args){
String str = " The Big House is";
PrintStream ps = new PrintStream(System.out);
ps.printf("My name is : %s White", str);
ps.flush();
ps.close();
}
}
Output is : The Big House is White
The other way to use PrintStream is...
CharSequence cq = "The Big House is White";
PrintStream ps = new PrintStream(System.out);
ps.append(cq);
ps.flush();
ps.close();
}
}
This might sound flippant, but PrintStream prints to an OutputStream, and PrintWriter prints to a Writer. Ok, I doubt I'll get any points for stating the obvious. But there's more.
So, what is the difference between an OutputStream and a Writer?
Both are streams, with the primary difference being a OutputStream is a stream of bytes while a Writer is a stream of characters.
If an OutputStream deals with bytes, what about PrintStream.print(String)? It converts chars to bytes using the default platform encoding. Using the default encoding is generally a bad thing since it can lead to bugs when moving from one platform to another, especially if you are generating the file on one platform and consuming it on another.
With a Writer, you typically specify the encoding to use, avoiding any platform dependencies.
Why bother having a PrintStream in the JDK, since the primary intent is to write characters, and not bytes? PrintStream predates JDK 1.1 when Reader/Writer character streams were introduced. I imagine Sun would have deprecated PrintStream if only for the fact it is so widely used. (After all, you wouldn't want each call to System.out to generate a deprecated API warning! Also, changing the type from PrintStream to PrintWriter on the standard output streams would have broken existing applications.)
Since JDK 1.4 it's possible to specify the character encoding for a PrintStream. Thus, the differences between PrintStream and PrintWriter are only about auto flushing behavior and that a PrintStream cannot wrap a Writer.