Search This Blog

Tuesday, 9 September 2014

Read File - JAVA

How to Read file in Java - File Handling in java

To read file in Java, we use the nextLine() function of scanner to get string up til enter. And do this in loop untill end of file using hasNext().

This program shows how to Read a file in Java..

Main.java

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


public class Main {
 public static void main(String args[]){
  Scanner scanner;
  try {
   scanner = new Scanner(new File("myFile.txt"));
   
   while (scanner.hasNext()){
    System.out.println(scanner.nextLine());
   }
   
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }  
 }
}

No comments:

Post a Comment