Search code examples
javafinite-automatafsmstate-machine

Parsing file using finite state machine


I am implementing my own fsm to parse a file. I am new to fsm pattern so trying to learn about it.

My fsm class takes a stream of the file that is being parsed along with the current state and a collection of all accepting states.

Now I am confused about couple of things.

  1. How does the fsm move through states and keep track of what has been parsed so far?

  2. What information should the state object store? Right now they have a pattern that they match on the line and see if fsm can move to this state or not.

Example:

File to parse:

Person:  bob smith
        Age: 33
        Location: new York
End person
Person:  Jane smith
        Age: 66
        Location: Chicago
End person

So I have a state for person start, age, location and end person. Each state object has a patter. (regex) to check if the given line is accepted by them or not.

But I am stuck on how would I construct a Person object when parsing this file using fsm??


Solution

  • Have a list of persons (empty initially). Have a currentPerson variable.

    • When the state is "person start", initialize the currentPerson variable to a new Person.
    • When the state is "age", set the age into the currentPerson.
    • Same for the "location" state.
    • When the state is "end of person", add the currentPerson to the list of persons.

    When you reach the end of the file, the list of persons contains all your persons.