JAVA——读取文本文件的倒数第N行(模拟Linux中tail命令)
生活随笔
收集整理的這篇文章主要介紹了
JAVA——读取文本文件的倒数第N行(模拟Linux中tail命令)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
解決方案
1、引入jar包commons-io.jar
/*** 讀取文件的倒數第3行,并打印其內容*/import java.io.File; import java.io.IOException;import org.apache.commons.io.input.ReversedLinesFileReader;public class ReversedLinesFileReaderExample {public static void main(String[] args) throws IOException {File file = new File("D:\\file1.txt");int n_lines = 3;int counter = 1;//構造方法 ReversedLinesFileReader(final File file, final int blockSize, final String encoding) ReversedLinesFileReader object = new ReversedLinesFileReader(file, 4096, "UTF-8");while (counter <= n_lines) {if (counter == n_lines) {System.out.println(object.readLine());}object.readLine();//讀取下一行counter++;}}}2、?RandomAccessFile類
import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile;public class FromEndRF {public static void read(String filename) {read(filename, "GBK");}public static void read(String filename, String charset) {RandomAccessFile rf = null;try {rf = new RandomAccessFile(filename, "r");long len = rf.length();long start = rf.getFilePointer();long nextend = start + len - 1;String line;rf.seek(nextend);int c = -1;while (nextend > start) {c = rf.read();if (c == '\n' || c == '\r') {line = rf.readLine();if (line != null) {System.out.println(new String(line.getBytes("ISO-8859-1"), charset));}else {System.out.println(line);}nextend--;}nextend--;rf.seek(nextend);if (nextend == 0) {// 當文件指針退至文件開始處,輸出第一行System.out.println(rf.readLine());}}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (rf != null)rf.close();} catch (IOException e) {e.printStackTrace();}}}public static void main(String args[]) {read("d:\\2.txt", "gbk");} }參考文章
使用java讀取文本文件的倒數第N行
JAVA如何實現從最后一行讀取文件
總結
以上是生活随笔為你收集整理的JAVA——读取文本文件的倒数第N行(模拟Linux中tail命令)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JAVA——仿Linux命令行文件管理系
- 下一篇: JAVA——文件操作工具类封装的简单实现