Java I/O How to - Use Scanner to read several different unknown types of data








Question

We would like to know how to use Scanner to read several different unknown types of data.

Answer

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
/*from ww w. j ava 2s.c o m*/
public class MainClass {
  public static void main(String args[]) throws IOException {
    // Write output to a file.
    FileWriter fout = new FileWriter("test.txt");
    fout.write("int: 1  double 1.0  boolean true");
    fout.close();

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

    Scanner src = new Scanner(fin);

    while (src.hasNext()) {
      if (src.hasNextInt()) {
        System.out.println("int: " + src.nextInt());
      } else if (src.hasNextDouble()) {
        System.out.println("double: " + src.nextDouble());
      } else if (src.hasNextBoolean()) {
        System.out.println("boolean: " + src.nextBoolean());
      } else {
        System.out.println(src.next());
      }
    }
    fin.close();
  }
}

The code above generates the following result.