读末尾两行 java读txt_java读取文件最后N行

指定行数,可以获取到从这行到文件尾的所有行,分享自大熊。

源文件:

e34d6ac0f7f6f056d042886aab214501.png

读取最后10行结果

20140118235302035_650x325.jpg

import java.io.File;

import java.io.IOException;

import java.io.RandomAccessFile;

import java.util.ArrayList;

import java.util.List;

/**

*

* 文件读取类

*

* @author 大熊 www.zuidaima.com

* @version [1.0, 2013-7-24]

* @since [面试/1.0]

*/

public class ReadFile

{

//Main函数,程序入口

public static void main(String[] args)

{

//调用读取方法,定义文件以及读取行数

readLastNLine(new File("D:\\apache-tomcat-7.0.40\\RUNNING.txt"), 10L);

}

/**

* 读取文件最后N行

*

* 根据换行符判断当前的行数,

* 使用统计来判断当前读取第N行

*

* PS:输出的List是倒叙,需要对List反转输出

*

* @param file 待文件

* @param numRead 读取的行数

* @return List

*/

public static List readLastNLine(File file, long numRead)

{

// 定义结果集

List result = new ArrayList();

//行数统计

long count = 0;

// 排除不可读状态

if (!file.exists() || file.isDirectory() || !file.canRead())

{

return null;

}

// 使用随机读取

RandomAccessFile fileRead = null;

try

{

//使用读模式

fileRead = new RandomAccessFile(file, "r");

//读取文件长度

long length = fileRead.length();

//如果是0,代表是空文件,直接返回空结果

if (length == 0L)

{

return result;

}

else

{

//初始化游标

long pos = length - 1;

while (pos > 0)

{

pos--;

//开始读取

fileRead.seek(pos);

//如果读取到\n代表是读取到一行

if (fileRead.readByte() == '\n')

{

//使用readLine获取当前行

String line = fileRead.readLine();

//保存结果

result.add(line);

//打印当前行

System.out.println(line);

//行数统计,如果到达了numRead指定的行数,就跳出循环

count++;

if (count == numRead)

{

break;

}

}

}

if (pos == 0)

{

fileRead.seek(0);

result.add(fileRead.readLine());

}

}

}

catch (IOException e)

{

e.printStackTrace();

}

finally

{

if (fileRead != null)

{

try

{

//关闭资源

fileRead.close();

}

catch (Exception e)

{

}

}

}

return result;

}

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值