How can I parse a text file?

Hi all, I have a file call default.cfg , it is actually a simple text file with the following format:

#define ContactSurname=William
#define ContactGiven=Bob
#define ContactPhone=1234567890
#define ContactExt=123
#define EntityName=secret101
#define Street=12 street
#define City=San Francisco
#define Country=USA
#define Zip=123456

and so on and so on.

My question is, how could I create a java program to parse these values such that I could call

return findValue("ContactSurname") then my result would be "William"?
fylix0000Asked:
Who is Participating?
 
BogoJokerCommented:
Hi fylix0000,

Here are the basics of reading a file:http://www.javaalmanac.com/egs/java.io/ReadLinesFromFile.html

If you take the code that is there, you can edit it like this in your findValue function, like so:
You can write this a number of ways, I will make findValue() require the filename and the key your looking for:

public String findValue(String filename, String key)
{
    try
    {
        BufferedReader in = new BufferedReader(new FileReader(filename));
        String str;
        while ((str = in.readLine()) != null)
        {
            if (str.indexOf("#define " + key) != -1)
            {
                in.close();
                return str.substring(str.indexOf("=")+1);
             }
        }
        in.close();
        return null;
    } catch (IOException e) {}
    return null; // <--- this will also happen if there is an IOException, Like file not found
}

Now, you would use that function like:
String surname = findValue("default.cfg", "ContactSurname");  // <-- surname will be William
String willNotFind = findValue("default.cfg", "BlahBlahBlah"); // <-- willNotFind will be null

I hope that helps, any questions on my code or modifications that need to be made?

Also I would suggest you look into Properties files.  It basically lets you do exactly what you want but Java has already made all the code for you.  Check it out:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Properties.html
Example Usage:
http://www.javaalmanac.com/egs/java.util/Props.html?l=rel

Really nice and easy with Properties Files
Joe P
0
 
fylix0000Author Commented:
Thank you very much Joe, this solution is exact to the point and simple to do.........two thumbs up
0
 
BogoJokerCommented:
Thanks, I'm learning how to answer questions better and better. =)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.