Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

how to read a text file and return a specifc record?

Posted on 2006-05-20
8
Medium Priority
?
243 Views
Last Modified: 2010-03-31
I have a text file with ; as delimiter. Each record contains first name, last name, phone number and extension. How can I search a record with first name as "John" and last name as "Smith".  And how can I search all records if last name is "Smith" ?  

It may sound easy to you, but I have done a lot of searching and can't find the answer. Please help.
0
Comment
Question by:Wonder19
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 14

Expert Comment

by:hoomanv
ID: 16725132
post first few lines of input file to see what structure it has
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 16725136
http://javaalmanac.com/egs/java.io/ReadLinesFromFile.html

to read the file

Use a class like this (you'll have to add the fields)

public class Person {
      public Person(String[] args) {
            this.firstName = args[0];
            this.lastName = args[1];
            // (etc)
      }
}

You can make the process method shown at the link

public void process(String line) {
      people.add(new Person(line.split(";")));
}

'people' would be a Set or List you create before the file is read

To find surname 'Smith' you can do

List smiths = new ArrayList();
Iterator i = people.iterator();
while (i.hasNext()) {
      Person p = (Person)i.next();
      if ("Smith".equals(p.getLastName())) {
            smiths.add(p);
      }
}
0
 

Author Comment

by:Wonder19
ID: 16725282
Dear CEHJ,

Sorry that I'm so junior in Java programming. I found the URL you posted, but I don't understand well.  Where should I put the open file try catch block in your suggested Person class?  Would you please provide more detail on "'people' would be a Set or List you create before the file is read". Thanks a ton!

try {
        BufferedReader in = new BufferedReader(new FileReader("infilename"));
        String str;
        while ((str = in.readLine()) != null) {
            people.add(new Person(line.split(";")));
        }
        in.close();
    } catch (IOException e) {
}
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Accepted Solution

by:
ctamrakar earned 1000 total points
ID: 16725296
// read the text file
// for eg your file have lines  as--
// firstname,lastname,Phoneumber

FileReader file_reader = new FileReader("c:\\file.txt");
BufferedReader in = new BufferedReader (file_reader);
                           
           do  {              
                 // read the line
                  line = in.readLine();
                  if (line!=null){
                    // tokenize the file
                    StringTokenizer st = new StringTokenizer(line,",");
                 
                 while (st.hasMoreElements()){
                         //tokenize the elements in line
                         String first = st.nextToken();
                         String last = st.nextToken();
                         String Phonenum = st.nextToken();
                        if   ( first.equals("firstname") and last.equals("lastname")) {
                              // do something  i found the record
                              // you can hv condition as you like
                             }          
     
                 }
           }

          }
              // read till end of file
             while (line != null);


I hope this helps :)


chandan
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 16725412
>>Where should I put the open file try catch block in your suggested Person class?

You don't put it in the Person class. You can put it in your main class. Call it getPeople say.

public void getPeople() {
    // File reading code here
}

You can put the Set or List in the constructor

public class YourClass {
    private List people;

    public YourClass() {
        people = new ArrayList();
    }

    public void getPeople() {
        // File reading code here
    }
}
0
 

Author Comment

by:Wonder19
ID: 16725420
Dear ctamrakar,

Sorry to be a pain in the neck. Your comment is very help. But I'm not smart enough to complete this task without your help. I set a String record = "";  then ...
....
if   ( first.equals("firstname") and last.equals("lastname")) {
    // find the record(s) which has the conditions
     record += line;
}      
....
while (line != null);
System.out.println("Record = " + record);

But there is no record returned. I checked my file, firstname & lastname are in the same record and they are spelling the same.  Did write space count? Any idea?




0
 

Author Comment

by:Wonder19
ID: 16725504
Dear ctamrakar,

I found that if I search for only one matching field, it returns at least a record.  But I can't search a record with two fields in a record.  Did I miss anything?

Dear CEHJ,

Thanks for your explanation. I will keep it in mind.
0
 
LVL 1

Expert Comment

by:ctamrakar
ID: 16726847
Dear wonder19,

Can i know how many fields you have in text file ? what is the format of ur file
may be you got some exception and program never went into if loops.



chandan Tamrakar


-----------

Sorry to be a pain in the neck. Your comment is very help. But I'm not smart enough to complete this task without your help. I set a String record = "";  then ...
....
if   ( first.equals("firstname") and last.equals("lastname")) {
    // find the record(s) which has the conditions
     record += line;
}      
....
while (line != null);
System.out.println("Record = " + record);

But there is no record returned. I checked my file, firstname & lastname are in the same record and they are spelling the same.  Did write space count? Any idea?
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses
Course of the Month11 days, 2 hours left to enroll

572 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question