File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes I/O in Java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "I/O in Java" Watch "I/O in Java" New topic

I/O in Java

chander shivdasani
Ranch Hand

Joined: Oct 09, 2007
Posts: 206

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?

Enjoy, Chander
SCJP 5, Oracle Certified PL/SQL Developer
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46437
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

Joined: Jan 03, 2004
Posts: 6109

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).
I agree. Here's the link:
subject: I/O in Java
It's not a secret anymore!