0

Let's say that we have a this text file with animals and their color:

dog=brown
cat=yellow
bird=red

I need to get the color of the animal, so i wrote this method. I call the method with the animal i want the color of in the parameter.

public String getAnimal(String animal) throws IOException{
        Scanner sc = new Scanner(TEXT_FILE).useDelimiter("=");
        for (int i = 0; i < 3; i++){
            if(sc.nextLine().startsWith(animal)){
                sc.next();
                return sc.next();
            }
            sc.nextLine();
        }
         return null;
    }

It only semi works. For example calling System.out.println(getAnimal("cat"));, prints:

yellow
cat

It's like if the scanner ignored the fact that there are any lines and prints anything between the delimiters.

abandoned
  • 61
  • 6
  • I don't understand the question. Or there is no question at all. – Rohit Jain Feb 20 '13 at 05:40
  • 1
    If this is the input format you are expecting, you case use `Properties` class (http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html) – Apurv Feb 20 '13 at 05:53

1 Answers1

0

If this is the input format you are expecting, you case use Properties class (docs.oracle.com/javase/6/docs/api/java/util/Properties.html)

OR

You can use Apache FileUtils.readLines to read all the lines. Then split the strings using String.split and = character to separate the key - value pairs.

Apurv
  • 3,615
  • 3
  • 28
  • 49
  • I just want to get whats on a specific line. Is there any way to do this without using any external API? – abandoned Feb 20 '13 at 23:32
  • You can refer http://stackoverflow.com/a/4716623/960778 to read a text file line by line, then for every line look for the input key (dog/cat/bird) – Apurv Feb 21 '13 at 06:20