java读取文件最后N行
来源:互联网 发布:js三位随机数 编辑:程序博客网 时间:2024/05/10 08:06
原文:java读取文件最后N行
源代码下载地址:http://www.zuidaima.com/share/1550463669226496.htm
指定行数,可以获取到从这行到文件尾的所有行,分享自大熊。
源文件:
读取最后10行结果
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<String> */ public static List<String> readLastNLine(File file, long numRead) { // 定义结果集 List<String> result = new ArrayList<String>(); //行数统计 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; }}
1 0
- java读取文件最后N行
- 读取文件最后N行
- Java读取文件的最后n位
- python读取文件最后n行
- Python读取大文件的最后N行
- java 读取文件的最后若干行
- java读取文件后n行
- java 中读取文件最后一行信息
- java 倒序读取文件(最后一行开始读取)
- 读取文件的最后十行
- fseek读取大文件最后几行
- php读取超大文件最后几行
- php---读取大文件最后几行
- Java读取文件创建时间和最后修改时间
- Java读取文件创建时间和最后修改时间
- 高效读取文件最后一行
- python 读取文件最后一行
- C++ 读取文件最后一行
- 编辑器豆绿色
- CentOS 6.5 安装Gnome桌面环境
- Android之Activity滑动关闭(销毁)
- UITabBarController使用详解
- Android瀑布流照片墙实现,体验不规则排列的美感
- java读取文件最后N行
- 绿色版Oracle环境变量设置
- Codeforces 508C - Anya and Ghosts (模拟 + 贪心)
- Android测试中能用到的一些脚本
- Php通过gsoap调用c++ websevice
- javascrit等号的转换和相等性
- [Jenkins 实战]关于Jenkins+Git部署的几点注意事项
- 通过feature自动将jar转成bundle
- sql server 一些时间函数