This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Write flat file in Fixed field length format  RSS feed

amar verma
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I need to write a java program who reads data from database and writes data in a flat file(.txt).
Format of the .txt file would be fixed length, no delimiter, space can be used wherever required.

Each field has maxlength defined and offset(column number from where it should start).

Data to be written has fields of all data types, i.e. string, char, long etc.

Currently i am using for this
approach is , convert all fields to strings, then strins to bytes,
then take a byte of size record length, write all bytes in this array at desired location, fill space wherever required.

then write this bytearray to RandomAccessFile.

I'm wandering if i am using right I/O stream or not, because we can open RandomAccessFile in either read only mode or read/write mode.
I need it just for write only mode.

any inputs pls.

Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sounds like that should work. I'd be a bit worried about the conversion from String to byte array and back when somebody reads it again. There are characters that won't make the translation both ways.

I'd probably convert fields to string, pad to length, and just write() with a normal output writer, mostly because I've been doing the same thing in other languages for years. Your byte array manipulation is probably more efficient but I'd try to stay with all Strings for comfort. If you always append to the end of the file random access file may be a bit of overkill. If you overwrite existing records, RAF and your fixed length records are perfect for the job.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!