Java Java Data Structures Efficiency! Custom Serialization

PrintWriter vs. FileWriter

I've noticed Craig uses PrintWriter to write to file instead of FileWriter. I've done some research on the differences, but haven't found a clear answer. What advantages are there to wrapping a FileWriter in a PrintWriter instead of using FileWriter directly? If it's situational, when is FileWriter preferred and when is PrintWriter preferred? Thanks!

I'll take a wild guess and say PrintWriter is good for txt files with Strings in them, while FileWriter is for java and other types of files. hope I've helped.

1 Answer

Courtney Wilson
Courtney Wilson
1,687 Points

FileWriter's write() method that accepts a String only writes a portion of a String to a file. Syntax:

write(String str, int off, int len)

The starting position (int off) and number of characters to write (int len) must be known. I've used the write() method with BufferedWriter for a String where I knew the amount of characters. For the Karaoke example (where the length is not known) PrintWriter is better suited.