Results 1 to 2 of 2
- 08-04-2012, 10:33 PM #1
Member
- Join Date
- Jan 2012
- Posts
- 24
- Rep Power
- 0
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"); } } }
- 08-04-2012, 10:50 PM #2
Senior Member
- Join Date
- Oct 2010
- Location
- Germany
- Posts
- 780
- Rep Power
- 4
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
-
Getting specific values from a file
By M0RT in forum New To JavaReplies: 2Last Post: 02-16-2012, 06:24 AM -
Printing to the screen specific lines from a file
By stevenhaynes5 in forum New To JavaReplies: 9Last Post: 08-15-2011, 05:28 PM -
Log4J : logs of a specific category to a file, but only errors to the file AND stdout
By msegmx in forum Advanced JavaReplies: 0Last Post: 07-15-2010, 01:23 PM -
Counting specific word from a file
By jaq in forum New To JavaReplies: 2Last Post: 12-02-2009, 06:12 PM -
how do i print a specific txt file on a specific printer
By nikhilbhat in forum New To JavaReplies: 2Last Post: 11-08-2008, 10:40 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks