Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Java Scanner from String File/Path InputStream

Java Scanner read from String File/Path InputStream

In this tutorial we’re going to show how to use Java Scanner to read data from different input sources – String, File/Path, and InputStream.

The basic use of java.util.Scanner is like this:

try (Scanner scanner = new Scanner(input)) {
   // process data

We use try with resources to close the scanner, which automatically closes input if it implements Closeable interface.

Scanner read from String

Scanner can be used to read input data from simple Strings:

try (Scanner scanner = new Scanner("1 2 3 5 8 13")) {
    int sum = 0;
    while (scanner.hasNextInt()) {
        sum += scanner.nextInt();
    System.out.println("Sum of numbers: " + sum);

The above example generates:

Sum of numbers: 32

Scanner read from File/Path

To read from use new File(“filename”):

Path source = Paths.get("/proc/meminfo");
System.out.println("Reading from file: " + source);
try (Scanner scanner = new Scanner(source)) {
    while (scanner.hasNext()) {

Cut output of the above code:

Reading from file: /proc/meminfo
MemTotal:        8064000 kB
MemFree:          266620 kB
MemAvailable:    3502160 kB

Scanner read from InputStream

Notice the change of delimiter to comma (,):

byte[] data = "one,two,three".getBytes();
InputStream source = new ByteArrayInputStream(data);
try (Scanner scanner = new Scanner(source)) {
    while (scanner.hasNext()) {

The above code produces:



Share with the World!