How to get rid of empty lines in a file?

How can read a file "text.txt", delete all the empty lines and restore it to same filename "text.txt" without using a temporary file?
[140 byte] By [Jakepaloa] at [2007-11-26 13:16:22]
# 1

It really isn't very sensible to try and do this kind of editing on a text file "in place". If the file is a sensible length you could simply read the whole thing into memory, remove the blank lines, and overwrite the original file.

You may need to give some thought to what happens to the file if the program doesn't complete.

In principal you could map the file into a ByteBuffer (via RandomAccessFile -> FileChanel) and change it in place. You'd tranfer bytes using a read and a write offset into the buffer, deleting is actually less messey than inserting would be. At the end you'd need to truncate the file.

However it would be more efficent to create a new file, then rename the old and new versions so that the new version replaced the old.

malcolmmca at 2007-7-7 17:38:15 > top of Java-index,Java Essentials,Java Programming...
# 2

Ages ago I ruined an 8" floppy disk drive by doing something similar to

this: let b1 b2 ... bn nl be a series of blanks followed by a newline

character (nl) and let c1 ... cm be a sequence of other characters. Let

the total relevant sequence be:

b1 b2 ... bn nl c1 ... cm

Reverse the entire sequence: cm ... c1 nl bn ... b2 b1 and then

reverse the first m bytes: c1 cm nl bn ... b2 b1. Now repeat the entire

thing for the sequence c1 ... cm by checking for more blank lines in it.

After this has all finished, simply truncate the file.

The advantage of this method was that I only needed to be able to swap

two bytes in a file; the disadvantage was that the floppy disk drive

couldn't handle it ;-)

kind regards,

Jos

JosAHa at 2007-7-7 17:38:15 > top of Java-index,Java Essentials,Java Programming...