熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

JAVA如何實現從最後一行讀取文件

2022-06-13   來源: Java核心技術 

  JAVA如何實現從最後一行讀取文件

  import javaioFileNotFoundException;

  import javaioIOException;

  import javaioRandomAccessFile;

  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 = rflength()

  long start = rfgetFilePointer()

  long nextend = start + len ;

  String line;

  rfseek(nextend)

  int c = ;

  while (nextend > start) {

  c = rfread()

  if (c == \n || c == \r) {

  line = rfreadLine()

  if (line != null) {

  Systemoutprintln(new String(linegetBytes(ISO charset))

  }else {

  Systemoutprintln(line)// 輸出為null可以注釋掉

  }

  nextend;

  }

  nextend;

  rfseek(nextend)

  if (nextend == ) {// 當文件指針退至文件開始處輸出第一行

  Systemoutprintln(new String(rfreadLine()getBytes(ISO charset))

  }

  }

  } catch (FileNotFoundException e) {

  eprintStackTrace()

  } catch (IOException e) {

  eprintStackTrace()

  } finally {

  try {

  if (rf != null)

  rfclose()

  } catch (IOException e) {

  eprintStackTrace()

  }

  }

  }

  public static void main(String args[]) {

  read(d:\\txt gbk

  }

  }


From:http://tw.wingwit.com/Article/program/Java/hx/201311/26379.html
  • 上一篇文章:

  • 下一篇文章:
  • 推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.