Home‎ > ‎Applied Core Java‎ > ‎Basic I/O‎ > ‎

Read File By Scanner

Problem - How you can read a text file from a directory ?

Solution :
java.util.Scanner which can parse primitive types and strings using regular expressions.

Program :

Step 1 - Coding

Create a text file c:/sunilos/ReadFileScanner.java  and copy below contents.

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

/**
 * A program to read a file with help of Scanner class.
 */ 

public class ReadFileScanner {

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

        FileReader reader = new FileReader("c:/sunilos/sunilos.txt");
        //Scanner sc = new Scanner("c:/sunilos/sunilos.txt");
        Scanner sc = new Scanner(reader);
        while(sc.hasNext()){
            System.out.println(sc.nextLine());
        }
       
    }

}

Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy ReadFileScanner.java  into 'c:\sunilos' folder.
  3. Download sunilos.txt file into 'c:\sunilos' folder.
  4. Open your command prompt and go to  'c:\sunilos'
  5. Compile ReadFileScanner.java with help of 
    1. javac ReadFileScanner.java command.Command will create ReadFileScanner.class file in the same folder.
  6. Congratulations!! your Java program is ready to serve.

Step 3 - Testing

  1. Make sure you are on Command Prompt under c:\sunilos directory
  2. Now start your java program from command prompt with help of 
    • java ReadFileScanner command.

Output


A software services and corporate training company specializing in Distributed
Object Oriented and Client Server Technologies with a strong background of J2EE.


<<Previous | Next>>
ċ
ReadFileScanner.java
(1k)
Mahima Hardia,
Aug 19, 2011, 2:30 AM
Comments