One problem with your current code is you are trying to overwrite the file every time. Essentially, here's the steps you'll need to take 1. Open the input file A 2. Create an output file B 3. Loop over every line in A a. If it DOES NOT start with "Page", write the current line to file B b. If it DOES start with "Page", create your string buffer and write that to file B instead of the current line.
This should work based on your current design. You could do some performance tweaks to make it work better, but this should get you there. Hope this helps.