从文件末尾进行读取的简单示例

    现实中有时会遇到需要从文件末尾开始读取的例子,比如读取文件的最后一行之类的。

    此时需要采用 RandomAccessFile 进行读取。

    下面只是一个简单的倒序读取文件的示例,以供参考。此示例不考虑性能,只介绍RandomAccessFile 的使用方法。

import java.io.RandomAccessFile;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FromEndFileRead {
	public static void main(String args[]) {
		RandomAccessFile rf = null;
		try {
			rf = new RandomAccessFile("C:/net.log", "r");
			long len = rf.length();
			long nextend = len - 1;
			String line;
			rf.seek(nextend); //移动到文件最后
			int c = -1;
			while (nextend > 0) {
				c = rf.read();
				if (c == '\n' || c == '\r') {
					line = rf.readLine();
					if (line == null) {//处理文件末尾是空行的情况
						nextend--;
						rf.seek(nextend);
						continue;
					}
					System.out.println(new String(line.getBytes("ISO-8859-1"), "GB2312")); //处理中文问题
					nextend--;
				}
				nextend--;
				rf.seek(nextend);
				if (nextend == 0) {// 文件指针已退至开始处,输出第一行
					System.out.println(new String(rf.readLine().getBytes("ISO-8859-1"), "GB2312")); //处理中文问题
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				rf.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值