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 trialChaun Fogarty
9,803 PointsPrintWriter 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!
1 Answer
Courtney Wilson
8,031 PointsFileWriter'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.
Tal Idan
1,742 PointsTal Idan
1,742 PointsI'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.