Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Deleting last line in the file

1,343 views
Skip to first unread message

N.K.

unread,
Jul 2, 2003, 11:58:37 AM7/2/03
to
Hi, I was wondering if someone can help me with this...
I have a file object and I need to delete a last line of this file.
It's a large file, about 3000 rows or so and reading it line by line
is out of the question. Is there another way?
I appreciate your help.
Thanks
N.K.

Karthik A.

unread,
Jul 10, 2003, 7:55:03 AM7/10/03
to
Hi
you can use BufferedReader/Writer.... I have given the code example...
in-> is the input stream of the file
out-> file you want to pipe the output to .. can be same as the input file

BufferedReader d
= new BufferedReader(new InputStreamReader(in));
String final=new String();
while(true)
{
String currentLine=d.readLine();
if(currentLine==null)
{
break;
}
final=final+currentLine+'\r\n';
}
StringTokenizer strTokenizer=new StringTokenizer (final,'\r\n');
BufferedWriter w
= new BufferedWriter(new OutputStreamWriter(out));

for(int i=1;i<(strTokenizer.countTokens()-2);i++)
{
w.write(strTokenizer.nextToken()+'\r\n');
}

nad...@parkerglobal.com (N.K.) wrote in message news:<2d4502eb.03070...@posting.google.com>...

Message has been deleted

N.K.

unread,
Jul 14, 2003, 1:10:25 PM7/14/03
to
Thank you very much, it was very helpful.
N.K.


presc...@ftml.net (Sam Pinkerton) wrote in message news:<119cfa8d.03071...@posting.google.com>...
> Use java.io.RandomAccessFile. Search backward from the end of the
> file until you've located the end of the line preceding the last line.
> Then use the setLength() method to truncate the file after that
> character.
>
> It will be most efficient to read a chunk not too large but large
> enough to almost certainly fully contain the last line. Then search
> within the buffer. That avoids the overhead of repeatedly seeking and
> reading a single byte.
>
> You may need to consider what to do if the last line in the file does
> not end with a proper line end (e.g., the file might simply stop with
> no line termination). Whether the file is normal ASCII (ISO-8859) or
> something else (e.g., unicode or, worse, one of the UTF variants) may
> complicate things. Also, the second or only character of the line
> separator is not necessarily \n. See the system property
> line.separator. But if you know your environment you can be lazy and
> just look for the \n (or \r if on a Mac).

0 new messages