Scanner to read various types of data from a file.

This example shows how to use scanner to read various type(like integer, double, boolean, string) of data from a file.

import java.util.*;


class ScanMixed{

public static void main(String a[]) throws IOException {

int i;

double d;

boolean b;

String str;

//Write output to a file

FileWriter fout = new FileWriter("test.txt");

fout.write("Testing Scanner 10 12.2 one true two false");


FileReader fin= new FileReader("Test.txt");

Scanner src= new scanner(fin);

// Read to end.

while (src.hasNext()) {

if(src.hasNextInt()) {

i= src.nextInt();

System.out.println("int:  "+ i);


else if(src.hasNextDouble()) {

d= src.nextDouble ();

System.out.println("double: "+ d);


else if(src.hasNextBoolean()) {


System.out.println("boolean: "+b);


else {


System.out.println("String: "+ str);






2 thoughts on “Scanner to read various types of data from a file.

  1. Pretty nice post. I just stumbled upon your blog and wanted to say that I have really enjoyed browsing your blog posts. In any case I’ll be subscribing to your feed and I hope you write again soon!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s