• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to read from file and do compare the text from file  RSS feed

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have a text file as shown below:

Rice|Food
Coke|Drink


How do i check if it is Food then i will add Rice to food list else add to Drink list?
 
Bartender
Posts: 1840
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you tried anything yourself yet?

My first goal would be to read in the line as a String variable.
you should then be able to use String manipulation to work out the details. I assume the | character is being used as a delimiter here.
String methods such as indexOf, split and substring might all be applicable.
Once you have that, some simple if/then/else logic could work. Assuming that "food" and "drink" are the only things you are worrying about.

If there are unknown categories to consider, then you might have to use a data structure such as a Map

 
Marshal
Posts: 56610
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One hazard about String#split. It takes a regular expression as an argument, and the vertical bar/pipe symbol | is a metacharacter. Go through the Java™ Tutorials and see whether you have to escape it. You probably have to write "\\|" rather than "|".
 
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:You probably have to write "\\|" rather than "|".

Or "[|]" - which is may favourite, because then you don't have to worry whether the character is a meta or not (unless it's '[', ']' or '\'; or something like "\\s").

Choosing "\" as the escape character for Strings was one of Java's worst ever decisions, in my opinion.

Winston
 
Campbell Ritchie
Marshal
Posts: 56610
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Winston Gutkowski wrote:. . . Choosing "\" as the escape character for Strings was one of Java's worst ever decisions . . .
They didn't. They borrowed it from C and C++.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!