views:

684

answers:

5

Hello,

Does anybody know how to remove a line from a textfile.

I'm looking for something else than u read and write line by line and skip the line you want te remove.

For exemple: My File count 1346 lines and I want to remove line 520.

Thanks,
Martijn

A: 

You can read the entire file in, do a regex replace (given that you know the exact match etc) then write the file back out.

Personally I'm not sure of how much value this answer is :)

krystan honour
that is like the way I explained. I don't want to read and write.
Martijn Courteaux
ok i misunderstood your question
krystan honour
A: 

well, if you know the length (or the content of the last line):

long lastLineLength = lastLine.length();
RandomAccessFile raf = new RandomAccessFile("RandFile.txt", "rw");
long length = raf.length();
raf.setLength(length - lastLineLength );
raf.close();
stefita
this is more what I want but, it is just the last line
Martijn Courteaux
sorry, can't quite understand your comment
stefita
@stefita you remove only the last line. This is not the question, I guess he wants to remove an arbitrary line.
LB
yes, the author changed the description. The first draft was about the last line.
stefita
+2  A: 

Does the solution need to be written in Java? The UNIX commands sed and grep are made for just this purpose and will likely perform better. If you are running Windows, you can get access to these tools via Cygwin or there might be native ports out there.

Rob H
I agree, but I suspect that this question should have had a "homework" tag on it, hence it has to stay in java. (notice the letter 'O' in the number 52O, instead of 520.
Trevor Harrison
sorry about the O
Martijn Courteaux
+1  A: 

Yes. Rob is right. try this

sed -e '520d' <yourfile>

redirect the output to new file

here 520 is the line number you want to delete

Aviator
+4  A: 

A text file isn't something that supports zero-cost reorganization. It is simply a contiguous sequence of bytes. If you want to remove some bytes from the middle of the file (and by implication move all the following bytes up cover the removed bytes), you have to copy and re-write all those following bytes.

You have a few options. Read the entire file into memory, do your removal, and then write the file out. (hopefully to a temp file which you rename over on top of the original after successfully completing the write) Or do some fancy footwork with just reading in a buffers worth of data from the source file and doing some work on it.

Trevor Harrison
I was going to do the same comment: whatever the language, there is no magic to remove bytes in the middle of a file (in most OSes I know, at least). So I just +1 to your answer.
PhiLho