public class ReverseReaderFile {
private RandomAccessFile randomAccessFile = null;
private long length = 0;
private long index = 0;
private ReverseReaderFile(File file) throws IOException{
this.randomAccessFile = new RandomAccessFile(file, "r");
this.length = this.randomAccessFile.length();
this.index = this.length - 1;
}
public static ReverseReaderFile newInstance(String path) throws IOException{
return ReverseReaderFile.newInstance(new File(path));
}
public static ReverseReaderFile newInstance(File file) throws IOException{
if (file == null || !file.exists() || !file.isFile()){
return null;
}
return new ReverseReaderFile(file);
}
/**
* 获得文件长度
* @auther lupingui
* 2010-1-5 下午05:09:00
* @return
*/
public long getLength(){
return this.length;
}
/**
* 判断是否可继续往下读取
* @auther lupingui
* 2010-1-5 下午05:09:08
* @return
*/
public boolean next(){
return this.index >= 0;
}
/**
* 读取单行信息(去掉了回车换行)
* @auther lupingui
* 2010-1-5 下午05:09:34
* @return
* @throws IOException
*/
public String readLine() throws IOException{
StringBuffer line = new StringBuffer();
char c;
while(this.index >= 0){
this.randomAccessFile.seek(this.index);
c = (char)this.randomAccessFile.read();
this.index--;
if (c == '\n' || c == '\r'){
if (line.length() < 1){
continue;
}
break;
}
line.append(c);
}
return line == null ? null : line.reverse().toString();
}
/**
* 关闭输出流
* @auther lupingui
* 2010-1-5 下午05:15:19
* @throws IOException
*/
public void close() throws IOException{
this.randomAccessFile.close();
}
}
目前不能支持中文。
分享到:
2010-01-05 18:11
浏览 2888
评论