Don't do it yourself. Read http://stackoverflow.com/questions/10811194/is-there-a-simple-way-to-loop-over-stdin-in-guava Go over the comments regarding IOExceptions. See also JDK Scanner solution.