Java倒序读取文件信息

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();
	}
}

 

目前不能支持中文。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值