Exemple d’utilisation de la classe ‘Scanner’ pour lire un fichier texte

Author:


{filelink=4429}

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class LectureFichierAvecScanner {
  public static void main(String args[]) throws Exception {

    int i;
    double d;
    boolean b;
    String str;

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

    Scanner src = new Scanner(file);

    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()) {
        b = src.nextBoolean();
        System.out.println("boolean: " + b);
      } else {
        str = src.next();
        System.out.println("String: " + str);
      }
    }

    file.close();
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *