Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

I/O in Java

 
chander shivdasani
Ranch Hand
Posts: 206
Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There seem to be multiple ways of doing I/O in Java. How does one decide which one to use.
For example:

I can accept user's input through stdin in the following two ways:



Version 2:



I'm pretty sure there might be other ways to read the input as well. Are there any guidelines which i can follow when selecting which method to use?
 
Campbell Ritchie
Sheriff
Pie
Posts: 50277
80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Very briefly:

First suggestion: use the simplest you can. So Scanner is simpler to code than Buffering.
Second suggestion: Buffering is more efficient than simply using an input stream reader because you can read a whole line at a time, rather than a character at a time.
But Scanner has the advantage that it can return an int or a double directly, giving you added functionality.

I usually use a Scanner if I can. Occasionally it seems the BufferedReader or the BufferedWriter can read or write where Scanner and Formatter don’t seem to, so I use them.
There is another I/O method: the JOptionPane (input or message dialogue), which is much less popular than it used to be.

There are bound to be other ways to do it. Find a tutorial about the NIO2 classes in Java7.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Very briefly:

First suggestion: use the simplest you can. So Scanner is simpler to code than Buffering.


I agree with the suggestion, but the conclusion is subjective, and I happen to hold the opposing view. :-)

I can't stand Scanner. I never, ever use it, and every time I try to answer questions on it, I have to spend so much time in the Javadocs and playing with sample code that I wonder why anybody would want to get within a mile of it. But that's just my opinion. :-)

So, Chander, what you can take from this is that often there's not one "best" or even "simplest" way to do things. So use the approach that does meets your requirements in the manner that you personally find the simplest or easiest to understand (subject to any rules, conventions, or standards of your team, of course).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic