Jason Zhu
Jason Zhu

Reputation: 71

How to read the last line of an online file, from the end of file

all:

I wonder how to quickly read the last line of an online file, such as "http://www.17500.cn/getData/ssq.TXT",

I know the RandomAccessFile class, but it seems that it can only read the local files. Any suggestion ?? TKS in advance.

Upvotes: 2

Views: 237

Answers (1)

JB Nizet
JB Nizet

Reputation: 691765

You'll have to read through the whole reader, and only keep the last line:

String line;
String lastLine = null;
while ((line = reader.readLine()) != null) {
    lastLine = line;
}

EDIT: as Joachim says in his comment, if you know that the last line will never be longer than (for example) 500 bytes, you could set the Range header in your HTTP request to -500, and thus only download the last 500 bytes. The same algorithm as above could be used.

I don't know, however, if it would deal correctly a stream starting in the middle of a multi-byte encoded character if the encoding is multi-byte (like UTF-8). With ASCII or ISO-8859-1, you won't have any problem.

Also note that the server is not forced to honor the range request, and could retur the whole file.

httpConnection.setRequestProperty("Range","-500");

Upvotes: 3

Related Questions