delete/remove first line(s) in a text file

R

Rob Shepherd

Dear c.l.j.programmers,

I'd like to perform (efficiently) the removal of the first n lines
from a plain text file.

Does anybody have any suggestions

Cheers

Rob
 
V

visionset

Rob Shepherd said:
Dear c.l.j.programmers,

I'd like to perform (efficiently) the removal of the first n lines
from a plain text file.

Does anybody have any suggestions

To do exactly as you say you would need a RandomAccessFile - see API docs
there are readLine() and writeBytes(String) methods, so you would seek
forward x lines readLine and then seek back x lines to writeBytes, where x
is the number of lines you wish to skip and you would need to know the
length of these lines, because you know or by seeking 1 char at a time and
testing for line terminator.
So obviously this is a pain and proably slow, coupled with the fact that
properly buffered serial access is *very* fast, I'd just read from one file
then write it out to another.

new BufferedReader(new FileReader("mySourceFile.txt"));
new BufferedWriter(new FileWriter("myOutFile.txt"));
When you're done rename the file.
 
J

J

visionset said:
To do exactly as you say you would need a RandomAccessFile - see API docs
there are readLine() and writeBytes(String) methods, so you would seek
forward x lines readLine and then seek back x lines to writeBytes, where x
is the number of lines you wish to skip and you would need to know the
length of these lines, because you know or by seeking 1 char at a time and
testing for line terminator.
So obviously this is a pain and proably slow, coupled with the fact that
properly buffered serial access is *very* fast, I'd just read from one file
then write it out to another.

new BufferedReader(new FileReader("mySourceFile.txt"));
new BufferedWriter(new FileWriter("myOutFile.txt"));
When you're done rename the file.
If the file is small, why not just read the whole thing into an
ArrayList of type String then write back from element 1 to the last element?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top