Java世纪网 » JAVA技术整理板块 » Java 基础应用 » JDK » 从文件末尾逐行读取数据
import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; public class FromEndRF { public static void main(String args[]) { RandomAccessFile rf = null; try { rf = new RandomAccessFile("d:\\2.txt", "r"); long len = rf.length(); long start = rf.getFilePointer(); System.out.println(start); 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(); 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(); } } } }
系统管理员
管理员
查看此人帖子
kimi
铜牌会员
老紫竹