分享

java 倒序读取文件(最后一行开始读取)

 hh3755 2013-03-05
Java代码  收藏代码
  1. package cn.com.songjy.test.io;  
  2.   
  3. import java.io.FileNotFoundException;  
  4. import java.io.IOException;  
  5. import java.io.RandomAccessFile;  
  6.   
  7. /** 
  8.  * http://bbs.csdn.net/topics/190181198 
  9.  * 从最后一行开始读取 
  10.  */  
  11. public class FromEndRF {  
  12.   
  13.     /** 
  14.      *  
  15.      * @param filename 目标文件 
  16.      * @param charset 目标文件的编码格式 
  17.      */  
  18.     public static void read(String filename, String charset) {  
  19.   
  20.         RandomAccessFile rf = null;  
  21.         try {  
  22.             rf = new RandomAccessFile(filename, "r");  
  23.             long len = rf.length();  
  24.             long start = rf.getFilePointer();  
  25.             long nextend = start + len - 1;  
  26.             String line;  
  27.             rf.seek(nextend);  
  28.             int c = -1;  
  29.             while (nextend > start) {  
  30.                 c = rf.read();  
  31.                 if (c == '\n' || c == '\r') {  
  32.                     line = rf.readLine();  
  33.                     if (line != null) {  
  34.                         System.out.println(new String(line  
  35.                                 .getBytes("ISO-8859-1"), charset));  
  36.                     } else {  
  37.                         System.out.println(line);  
  38.                     }  
  39.                     nextend--;  
  40.                 }  
  41.                 nextend--;  
  42.                 rf.seek(nextend);  
  43.                 if (nextend == 0) {// 当文件指针退至文件开始处,输出第一行  
  44.                     // System.out.println(rf.readLine());  
  45.                     System.out.println(new String(rf.readLine().getBytes(  
  46.                             "ISO-8859-1"), charset));  
  47.                 }  
  48.             }  
  49.         } catch (FileNotFoundException e) {  
  50.             e.printStackTrace();  
  51.         } catch (IOException e) {  
  52.             e.printStackTrace();  
  53.         } finally {  
  54.             try {  
  55.                 if (rf != null)  
  56.                     rf.close();  
  57.             } catch (IOException e) {  
  58.                 e.printStackTrace();  
  59.             }  
  60.         }  
  61.     }  
  62.   
  63.     public static void main(String args[]) {  
  64.         read("mynewfile.txt""UTF-8");  
  65.     }  
  66. }  



引自:http://bbs.csdn.net/topics/190181198

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多