I am learning the basics of Java IO and cannot find what I would think would be covered in basic discussions of IO in java: without getting into subtleties or complexities (unless necessary), what is the very basic explanation of when you would choose one vs. when you would choose the other for output to a file (Formatter vs. FileOutputStream)?

I assume the same explanation will hold for Scanner vs. FileInputStream.

2 Answers

Laurent Pireyn On Best Solutions
  • You use an OutputStream (possibly a FileOutputStream) to write bytes.
  • You use a Formatter to write formatted text.

The first is very efficient but you have to know what bytes to write. The second gives you flexible formatting features, but is limited in what it can write, and is likely to be less efficient than the first.

Ted Hopp On

The Formatter and Scanner constructors that take file specifications as arguments are just a convenience for combining a file output or input stream with a Formatter or Scanner that operates on a stream. Use them whenever you were going to wrap your stream in a Formatter or Scanner anyway and you have no separate need for the stream object.