Results 1 to 2 of 2
  1. #1
    atac57 is offline Member
    Join Date
    Jan 2012
    Posts
    24
    Rep Power
    0

    Default Printing a specific name in a file? File I/O

    How can I get the program to print a string or number that a file contains? I'm trying to make my own database. I want to be able to search for a specific name and print out just that line of information. This code isn't doing what I expect. Thanks.


    names.txt:
    Bob Jones 5553912 San Jose, CA
    Carl Wilson 5553214 Houston, TX
    Jane Carter 5550711 Richmond, VA
    John Greene 5550996 Chicago, IL

    Java Code:
    import java.io.*;
    import java.util.Scanner;
    
    public class fileW {
    	public static void main(String[] args) {
    		
    		try{
    			BufferedReader reader = new BufferedReader(new FileReader("names.txt"));
    			String line = reader.readLine();
    			
    			while(line != null){
    				if(line.equals("Carl Wilson")){
    					System.out.println(line);
    					line = reader.readLine();
                        break;
    				}	 
    			}
    			reader.close();
    			
    		}catch(IOException iox){
    			System.out.println("Problem reading file");
    		}
    	}
    }

  2. #2
    eRaaaa is offline Senior Member
    Join Date
    Oct 2010
    Location
    Germany
    Posts
    786
    Rep Power
    5

    Default Re: Printing a specific name in a file? File I/O

    Bacause readLine reads the whole line, e.g. "Carl Wilson 5553214 Houston, TX" and that is NOT equal to "Carl Wilson"
    You could use contains -> if(line.contains("Carl Wilson"))
    But maybe it would be better if you read the whole file, parse the information and create objects and put them into a list ?!

Similar Threads

  1. Getting specific values from a file
    By M0RT in forum New To Java
    Replies: 2
    Last Post: 02-16-2012, 06:24 AM
  2. Printing to the screen specific lines from a file
    By stevenhaynes5 in forum New To Java
    Replies: 9
    Last Post: 08-15-2011, 05:28 PM
  3. Replies: 0
    Last Post: 07-15-2010, 01:23 PM
  4. Counting specific word from a file
    By jaq in forum New To Java
    Replies: 2
    Last Post: 12-02-2009, 06:12 PM
  5. Replies: 2
    Last Post: 11-08-2008, 10:40 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •