Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Data Structures - Retired 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
8,031 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.