String Parsing in Java

Started by
4 comments, last by Shakedown 15 years, 5 months ago
Hey forum, I'm looking for a solution to save the state of my program to a file, and be able to load it up again. Currently, all of my classes implement the "Stringable" interface, which specifies both a "toStringData()" and "fromStringData(String)" method. As long as a class and all of its components are "Stringable", you can turn them into Strings and write them out to a file. This has proved useful because class A containing some basic variables and instances of class B, C, and D, can store its variables and then call the "toStringData()" methods of B, C, and D. But delimiters are getting to be a problem. If Class D uses "," as a delimiter between function information, then any class that includes an instance of class D in it can't use it. This is because in the "fromStringData()" method of class D, it uses "s.split(",")" to get the contents of each piece of data in class D. If another class C were to use the same delimiter, it would also split up D's data. A saved structure ends up looking like this: "3,2,66;dummy;info,info2--324523~..." where "," ";" "--" and "~" are all delimiters. Any help?
Advertisement
how about in stead of using something as common as a comma, use another char sequence as your separators that you will never ever find in your data? I always use '|-|' for example.
Prepend "{" to every serialized block, append "}" to every serialized block.So, your example would serialize as:

{{{{3}{2}{66}}{dummy}{{info}{info2}}}{324523}

When deserializing, find all the top-level "{" (easy by counting how many unclosed "{" there are so far) and their matching "}".
Theres a serialization class/interface implemented in java for this very task; its been a while since I've looked at it though. (called serializable perhaps?)

http://java.sun.com/developer/technicalArticles/Programming/serialization/
http://www.fotofill.co.uk
Thanks for the helpful responses. I had shuddered when I first thought of the {} scheme, but counting the { and } is an obvious and easy solution.

I will also look into the serialization. Hopefully it's not too complicated!
Check out JSON as well. JSON is commonly used for serializing data and information into a String for communication between a client/server. The format is very simple (human-readable), there's no encryption, and there's full Java support. You wouldn't need to write anything yourself, just import the libraries write some serialization methods for your classes.

This topic is closed to new replies.

Advertisement