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"?
Who is Participating?
Hi fylix0000,

Here are the basics of reading a file:

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)
        BufferedReader in = new BufferedReader(new FileReader(filename));
        String str;
        while ((str = in.readLine()) != null)
            if (str.indexOf("#define " + key) != -1)
                return str.substring(str.indexOf("=")+1);
        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:
Example Usage:

Really nice and easy with Properties Files
Joe P
fylix0000Author Commented:
Thank you very much Joe, this solution is exact to the point and simple to do.........two thumbs up
Thanks, I'm learning how to answer questions better and better. =)
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.