Welcome to JavaRanch
You will realise we don't simply give out answers to that sort of exercise.
That looks a complicated bit of code, which ought to be in its own methods, not all in the main method. What sort of format are you writing these files in? Is it text or binary? Have you come across classes which buffer outputs and inputs? Or the newer classes, Scanner and Formatter? Have you looked at the
Java™ Tutorials where
you should find something useful?