We help IT Professionals succeed at work.

Read columns from a file ...

meow00
meow00 asked
on
Medium Priority
262 Views
Last Modified: 2010-03-31
Hello experts,

  I have a file:

  Name, gender, age, phone, address
  A,  F. 12, 123456, ABCDE
  B, M, 13, 111111, BCDEF
  :

 What would be the best (fast way) to read the data in the file and
 then put (Name, address) in a Hashmap ?

 thanks.
Comment
Watch Question

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
CERTIFIED EXPERT
Top Expert 2016
Commented:
Mayank SPrincipal Technologist
CERTIFIED EXPERT
Commented:
student
CERTIFIED EXPERT
Commented:
If your format will always remain the same, then you could use something like the following.  

import java.io.*;
import java.util.*;
public class meow {
  public static void main(String args[]) {
     try{
         BufferedReader br = new BufferedReader(new FileReader("meow00.txt"));
         HashMap map = new HashMap();
         String line = "this will hold current line";
         line = br.readLine(); // header not put
         while((line = br.readLine()) != null){
                                      String[] tokens = line.split(",");
                                      System.out.println(tokens.length);
                                      map.put(tokens[0].trim(),tokens[4].trim());
         }
         br.close();
         System.out.println(map);
        }catch(FileNotFoundException fnfe){System.out.println("fnfe");}
         catch(IOException ioe){System.out.println("ioe");}
  }
}
rrzstudent
CERTIFIED EXPERT

Commented:
Maybe you should add this line as well  
catch(ArrayIndexOutOfBoundsException e){System.out.println("problem with format");}
CERTIFIED EXPERT
Top Expert 2016

Commented:
:-)
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.