| Author |
How to read a formatted text file into objects
|
Kjeld Sigtermans
Ranch Hand
Joined: Aug 10, 2006
Posts: 111
|
|
Hello,
I have a text file that has a formatted structure containing 0-n lines, each line having the same length, containing properties, who each claim their own position in the line. For example, position 1 through 10 contains property A, position 11-16 contains property B, etc.
What would be an effective way to 'unmarshall' each line to an instance of a class containing property A, B, etc.? Other than explicitly programming to create a new instance, store pos 1-10 to property A, etc.?
E.g. this line:should result in an instance of a pojo having thePojo.getA() == "foo......?" and thePojo.getB() == "bar..!"
Obviously there is also the problem of how to assign each pojo property name to its corresponding property in the line.
Perhaps I should use XSLT or Freemarker to turn the file into XML and then unmarshall it?
Cheers,
Kjeld
|
Kjeld Sigtermans - SCJP 1.4 - SCWCD 1.4
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Since you know exactly how each line is built you can substring each line; for instance, after reading a line (BufferedReader comes into mind), you can use line.substring(0, 10), line.substring(10, 16), etc. The order is fixed as well, so it could be as simple as this:
Note that from a human's perspective String start at 1, but in Java (and most other programming languages) they start at 0. So if you say characters 1 to 10, in Java that's 0 to 9, and you use 10 as upper bound of substring because the upper bound is exclusive.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Kjeld Sigtermans
Ranch Hand
Joined: Aug 10, 2006
Posts: 111
|
|
Thanks Bob.
But what if I would not want to hardcode the positions in my Java code, and also not hardcode the mapping between line properties and object properties? Instead, specifying this in a mapping file of some sort.
As I said, this is the solution I try to avoid...
Other than explicitly programming to create a new instance, store pos 1-10 to property A, etc.?
Thanks,
Kjeld
|
 |
 |
|
|
subject: How to read a formatted text file into objects
|
|
|