2019独角兽企业重金招聘Python工程师标准>>>

File file = new File("DemoRandomAccessFile.out");
RandomAccessFile raf = new RandomAccessFile(file, "r");// Seek to the end of file
raf.seek(file.length() - n);
// Read it out.
raf.read(yourbyteArray, 0, n);

Below are two functions, one that returns the last non-blank line of a file without loading or stepping through the entire file, and the other that returns the last N lines of the file without stepping through the entire file:

What tail does is zoom straight to the last character of the file, then steps backward, character by character, recording what it sees until it finds a line break. Once it finds a line break, it breaks out of the loop. Reverses what was recorded and throws it into a string and returns. 0xA is the new line and 0xD is the carriage return.

public String tail( File file ) {RandomAccessFile fileHandler = null;try {fileHandler = new RandomAccessFile( file, "r" );long fileLength = fileHandler.length() - 1;StringBuilder sb = new StringBuilder();for(long filePointer = fileLength; filePointer != -1; filePointer--){fileHandler.seek( filePointer );int readByte = fileHandler.readByte();if( readByte == 0xA ) {if( filePointer == fileLength ) {continue;} else {break;}} else if( readByte == 0xD ) {if( filePointer == fileLength - 1 ) {continue;} else {break;}}sb.append( ( char ) readByte );}String lastLine = sb.reverse().toString();return lastLine;} catch( java.io.FileNotFoundException e ) {e.printStackTrace();return null;} catch( java.io.IOException e ) {e.printStackTrace();return null;} finally {if (fileHandler != null )try {fileHandler.close();} catch (IOException e) {/* ignore */}}
}

But you probably don't want the last line, you want the last N lines, so use this instead:

public String tail2( File file, int lines) {java.io.RandomAccessFile fileHandler = null;try {fileHandler = new java.io.RandomAccessFile( file, "r" );long fileLength = fileHandler.length() - 1;StringBuilder sb = new StringBuilder();int line = 0;for(long filePointer = fileLength; filePointer != -1; filePointer--){fileHandler.seek( filePointer );int readByte = fileHandler.readByte();if( readByte == 0xA ) {if (line == lines) {if (filePointer == fileLength) {continue;} else {break;}}} else if( readByte == 0xD ) {line = line + 1;if (line == lines) {if (filePointer == fileLength - 1) {continue;} else {break;}}}sb.append( ( char ) readByte );}sb.deleteCharAt(sb.length()-1);String lastLine = sb.reverse().toString();return lastLine;} catch( java.io.FileNotFoundException e ) {e.printStackTrace();return null;} catch( java.io.IOException e ) {e.printStackTrace();return null;}finally {if (fileHandler != null )try {fileHandler.close();} catch (IOException e) {/* ignore */}}
}

Another Example

public static void main(String[] args) throws Exception {int n = 3;List<String> lines = new ArrayList<>();try (RandomAccessFile f = new RandomAccessFile("test", "r")) {ByteArrayOutputStream bout = new ByteArrayOutputStream();for (long length = f.length(), p = length - 1; p > 0 && lines.size() < n; p--) {f.seek(p);int b = f.read();if (b == 10) {if (p < length - 1) {lines.add(0, getLine(bout));bout.reset();}} else if (b != 13) {bout.write(b);}}}System.out.println(lines);
}static String getLine(ByteArrayOutputStream bout) {byte[] a = bout.toByteArray();// reverse bytesfor (int i = 0, j = a.length - 1; j > i; i++, j--) {byte tmp = a[j];a[j] = a[i];a[i] = tmp;}return new String(a);
}

转载于:https://my.oschina.net/u/138995/blog/191402

JAVA IO - 高效读取大文件的后几行相关推荐

  1. Java高效读取大文件(转)

    Java高效读取大文件 1.概述 本教程将演示如何用Java高效地读取大文件.这篇文章是Baeldung(http://www.baeldung.com/) 上"Java--回归基础&quo ...

  2. java IO流读取保存图片文件

    java  IO流读取保存图片文件 package io; import java.io.BufferedInputStream; import java.io.BufferedOutputStrea ...

  3. Java高效读取大文件

    1.概述 本教程将演示如何用Java高效地读取大文件.这篇文章是Baeldung(http://www.baeldung.com/) 上"Java--回归基础"系列教程的一部分. ...

  4. java并发读取相同的文件_高效读取大文件,再也不用担心 OOM 了!

    最近阿粉接到一个需求,需要从文件读取数据,然后经过业务处理之后存储到数据库中.这个需求,说实话不是很难,阿粉很快完成了第一个版本. 内存读取 第一个版本,阿粉采用内存读取的方式,所有的数据首先读读取到 ...

  5. 高效读取大文件,再也不用担心 OOM 了!

    最近阿粉接到一个需求,需要从文件读取数据,然后经过业务处理之后存储到数据库中.这个需求,说实话不是很难,阿粉很快完成了第一个版本. 内存读取 第一个版本,阿粉采用内存读取的方式,所有的数据首先读读取到 ...

  6. 使用Apache Commons IO组件读取大文件

    Apache Commons IO读取文件代码如下: Files.readLines(new File(path), Charsets.UTF_8); FileUtils.readLines(new ...

  7. python高效读取大文件_python 如何读取大文件

    一般的读取文件的方法: with open(file_path, "r") as f: print f.read() 或者 with open(file_path,"r& ...

  8. java高性能线程读取大文件并分段分流翻译入库

    需求是一个每天读取单个文件在1个G到3G之间,数据量在400万左右,读取完成后,调用谷歌翻译成中文后,再保存到数据库 实现方面采用多线程,RandomAccessFile读取,缓冲区分流,其中还用到了 ...

  9. java io流读取txt文件_Java使用IO流读取TXT文件

    通过BufferedReader读取TXT文件 window系统默认的编码是GBK,而IDE的编码多数为UTF-8,如果没有规定new InputStreamReader(new FileInputS ...

  10. pandas高效读取大文件(csv)方法之-parquet

    一.数据类型轻量化 def reduce_df_memory(df):""" iterate through all the columns of a dataframe ...

最新文章

  1. 【问链财经-区块链基础知识系列】 第三十九课 EOS与ETH体系结构比较全解析
  2. SQLyog连接虚拟机中docker中的mysql过程详解,并解决2003错误
  3. 使用Live Writer和NNTP Bridge阅读微软论坛
  4. Jboss未授权访问漏洞记录(影响版本:全版本,端口:80,8080)
  5. html设置referer防盗链,referer与防盗链
  6. POJ 2886 Who Gets the Most Candies?
  7. rmt_redis.c:6446 ERROR: Can't handle RDB format version redis-migrate-tool迁移工具报错
  8. 安装一个自己的笔记软件——Wiz开源私有云笔记
  9. Windows常用运行库合集--官网(VC++、DirectX、.NET)
  10. Django serializer 方法补充之:depth 与字段生成超链接
  11. win10的windows聚焦锁屏界面图片在哪个文件夹的问题解决
  12. 微软重新评估收购雅虎提议
  13. Python实现特定格式的时间差自动计算
  14. python实战项目词云生成器(wordcloud+jieba+pyinstaller打包)——词云生成软件【Pyinstaller打包问题解决】
  15. C++11 使用智能指针封装 pimpl idom
  16. cpm、cpc、cps和cpa分别是什么意思
  17. Solr Filter过滤器
  18. 中国互联网著名天使投资人及投资领域
  19. 关于QQ通讯录的应用及vcf文件导入手机的乱码问题
  20. HTML链接:带超链接的网页

热门文章

  1. Spark安装和配置
  2. python字符串比较大小的规则_Python的变量和数据类型,学会只要3分钟
  3. 东北大学计算机学院拟录取分数线,东北大学全国各省各专业录取分数线汇总!(含艺术类)...
  4. 轻量级web api_哈尔滨Web前端基础学习规划
  5. 北理珠计算机学院罗晓莹,“职”等你来 | 计算机职业发展中心2020年见面大会,我们如期相遇~...
  6. 7-2 温度转换 (5 分)
  7. L1-019 谁先倒 (15 分) — 团体程序设计天梯赛
  8. 【Alpha】“北航社团帮”小程序v1.0发布声明
  9. 先查出已知的 然后将未知的当做 having里面的条件
  10. day1---流程控制语句的四种基本格式