Thursday, December 2, 2010

Read Text File Containing Email Addresses..

I wrote this small program to count email addresses in a text file. And to print email addresses one by one.

I use StringTokenizer class  to sort emails. You can use any character to sort out Strings.

For example, my file contains isuru@xcs.com; madusanka@qwe.com; roxniro@qwa.com... so I user ";" character to sort emails. You can use "@" character to collect user names of email addresses.

File Reader Class

import java.io.*;
import java.util.StringTokenizer;

public class FileReader {

    File file = new File("/root/Documents/emails.txt");
    StringBuffer contents = new StringBuffer();
    BufferedReader reader = null;
    String text = null;
    StringTokenizer st1;


    public void accessFile() {
        try{
             reader = new BufferedReader(new java.io.FileReader(file));
             while((text = reader.readLine()) != null){
                 st1 = new StringTokenizer(text, ";");
                 System.out.println("There are "+ st1.countTokens()+" email addresses!");
                 while(st1.hasMoreTokens()){
                     System.out.println(st1.nextToken());
                     
                 }
             }

        }catch(FileNotFoundException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }

    }

}

Main Class

/**
 *
 * @author Isuru
*/
public class EmailCounter {

    public static void main(String args[]){
        FileReader app = new FileReader();
        app.accessFile();

    }

}

No comments:

Post a Comment