Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Complex text-file-to-text-file conversion

 
Julien Martin
Ranch Hand
Posts: 384
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I have the following requirement:

I need to convert a text file with position-delimited fields to another text file with position-delimited fields.

For instance the first 8 characters represents the customer's birth date, then the following 10 characters the customer's first name and so on.



I want to be able to retrieve some of the customer's field ignoring others.

My question are as follows:
-What do you call this kind of files? (?? as opposed to comma-delimited text files)
-Do you know of any open-source libraries/api that could avoid me delving into low-level java?

Thanks in advance,

Julien Martin.
 
Ulf Dittmer
Rancher
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would call that kind of file a fixed-format text file. The task could be accomplished by a tool like AWK, but I'm not aware of a Java implementation (you could use the real thing via Runtime.exec, though).

But if you know exactly at which position a field starts and at which it ends, then accessing particular fields becomes as easy as using the String.substring method. That way there'd be no need to use any other API.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
These are fixed length records, familiar to all us old-timers raised on mainframes at least.

Let's start easy - read each line of the file into a String. From there you can get any field you like via substring() by knowing its starting byte and length.

birthDate = record.substring(0,10);
firstName = record.substring(11,8);
lastName = record.substring(19, 8);
etc.

If you're going to at least parse all the fields, you might build a little helper.

helper = new Helper( record );
birthDate = helper.next( 10 );
firstName = helper.next( 8 );
lastName = helper.next( 8 );
etc.

If you're going to make your living doing this for the next few years, you might build a much smarter parser, perhaps one that uses metadata and reflection to populate Java beans. Warning, this may be what you mean by "too low level" but it's good fun. Given data about a record, this utlity could read any file ...

Any of that sound useful? Can you imagine building the output record using the same information about field lengths?
 
Julien Martin
Ranch Hand
Posts: 384
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot for the reply!!
J.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic