Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

PrintWriter: passing File reference vs String  RSS feed

 
Aziza Korikova
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the difference between passing a PrintWriter a reference to a File object and passing it the String filename? If you just want to use the format method to write to a file, both arguments seem to do the same thing, but my instructor always passes a File object instead of just a String. Is that way better somehow?
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The end result is the same, but if you use a File object, you can do stuff head of time, like check if it exists and is readable/writable, deal with it cleanly if it's not, create the parent directories if needed, etc. If you just pass the String and it's not in a state where you can use it, you'll get an exception. If you don't care about that, or if you know everything is already ready before you start, then it doesn't matter.


I still usually prefer a File though, since it's a file I'm interested in, not some text. In other words, File more properly expresses my design intent, which makes for clearer code, which makes for easier understanding when somebody reads the code later, including me, who will have forgotten most of what I was doing by then.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!