read info from a file java code example

Example 1: java read text file

// java read text file with scanner
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class JavaReadTextFileScanner
{
   public static void main(String[] args) throws FileNotFoundException
   {
      File fl = new File("B:\demo.txt");
      Scanner sc = new Scanner(fl);
      while(sc.hasNextLine())
      {
         System.out.println(sc.nextLine());
      }
      sc.close();
   }
}

Example 2: java how to read a text file

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

class Scratch{
    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(new File("filename"));
        input.next();       //returns next String
        input.nextLine();   //returns next Line
        input.nextBoolean();//returns next Boolean
        input.nextInt();    //returns next Int
        input.nextDouble(); //returns next double
        ...
    }
}

Tags:

Java Example