Tuesday, October 16, 2012

Scanner to read a file and place each line in a List

Reading a file and place each line in a ArrayList
 
 
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author mreddy29
 */
public class FileR {
    
    public static void main(String d[])  
    {
        File file = new File("C:\\firstcontact\\HSRLOG.txt");
        
        Scanner scan = null;
        List list = new ArrayList();
        try {
            for( Scanner s = new Scanner(file).useDelimiter("\\n"); s.hasNext(); list.add(s.next()));
   
        }
        catch (FileNotFoundException ex) {
            System.out.println("FileNotFoundException raised");
        }
        catch ( Exception ex) {
            System.out.println(" Exception raised");
        }
       finally
       {
            try{ 
                scan.close(); 
            }
            catch(Exception exception)
            {
                System.out.println(" Exception raised while closing scanner object");
            }
       }
       System.out.println("List ="+list);
       
        
  }
    
}

No comments:

Post a Comment