Tuesday, October 16, 2012

Reading a File using Scanner Class

Scanner to read a file containing lines of structured data. Each line is then parsed using a second Scanner and a simple delimiter character, used to separate each line into a name-value pair. The Scanner class is used only for reading, not for writing.
It's worth remembering that Scanner will probably be a lot slower than a BufferedReader or BufferedInputStream, because it was designed to scan text, not read files.


import java.io.File;
import java.io.FileNotFoundException;import java.util.Scanner; 
public class ScannerReadFile { 
    public static void main(String[] args) { 
        // Location of file to read
        File file = new File("data.txt"); 
        try { 
            Scanner scanner = new Scanner(file); 
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } 
    }}
 
 
 
Scanner to read various types of data from a file
 
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class MainClass 
{  
    public static void main(String args[]) throws IOException 
    {   
        int i;    
        double d;  
        boolean b;   
        String str;   
        FileWriter fout = new FileWriter("test.txt");    
        fout.write("Testing Scanner 10 12.2 one true two false");    
        fout.close();    
        
        FileReader fin = new FileReader("Test.txt");    
        Scanner src = new Scanner(fin);    
        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);    
            }   
        }   
        fin.close();
    }
}    
 
 
 
 






No comments:

Post a Comment