Is there any way to do this without opening a new file and copy the whole text?
No there isn't. Certainly, there isn't if you want to do it safely.
And RandomAccessFile
won't really help you either. It would allow you to replace a sequence of bytes in the file with an equal number of bytes, but that doesn't amount to deleting a line.
You could use a RAF like this:
Given an initial state L1L2L3...LN
replace L2L3...LN
with L3...LN
or you could use the RAF to "slide" the lines one at a time as per @halfbit's answer.
However:
In the worst case you are copying the entire file content, and the average case involves reading and writing the bytes of O(N)
lines.
The simple way of doing this requires holding O(N)
lines in memory.
The "sliding" approach requires O(N)
I/O operations (i.e. system calls).
Most importantly: line deletion by in-place file update is risky. If the application is interrupted in the middle of the process (e.g. power failure), then you will end up with a corrupted file.
FWIW: this is not a limitation in Java per se. Rather it is a limitation of the way that modern operating systems represent / model files.