原文:java讀取檔案最後N行
源代碼下載下傳位址:http://www.zuidaima.com/share/1550463669226496.htm
指定行數,可以擷取到從這行到檔案尾的所有行,分享自大熊。
源檔案:
讀取最後10行結果
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;
/**
*
* 檔案讀取類
*
* @author 大熊 www.zuidaima.com
* @version [1.0, 2013-7-24]
* @since [面試/1.0]
*/
public class ReadFile
{
//Main函數,程式入口
public static void main(String[] args)
{
//調用讀取方法,定義檔案以及讀取行數
readLastNLine(new File("D:\\apache-tomcat-7.0.40\\RUNNING.txt"), 10L);
}
/**
* 讀取檔案最後N行
*
* 根據換行符判斷目前的行數,
* 使用統計來判斷目前讀取第N行
*
* PS:輸出的List是倒叙,需要對List反轉輸出
*
* @param file 待檔案
* @param numRead 讀取的行數
* @return List<String>
*/
public static List<String> readLastNLine(File file, long numRead)
{
// 定義結果集
List<String> result = new ArrayList<String>();
//行數統計
long count = 0;
// 排除不可讀狀态
if (!file.exists() || file.isDirectory() || !file.canRead())
{
return null;
}
// 使用随機讀取
RandomAccessFile fileRead = null;
try
{
//使用讀模式
fileRead = new RandomAccessFile(file, "r");
//讀取檔案長度
long length = fileRead.length();
//如果是0,代表是空檔案,直接傳回空結果
if (length == 0L)
{
return result;
}
else
{
//初始化遊标
long pos = length - 1;
while (pos > 0)
{
pos--;
//開始讀取
fileRead.seek(pos);
//如果讀取到\n代表是讀取到一行
if (fileRead.readByte() == '\n')
{
//使用readLine擷取目前行
String line = fileRead.readLine();
//儲存結果
result.add(line);
//列印目前行
System.out.println(line);
//行數統計,如果到達了numRead指定的行數,就跳出循環
count++;
if (count == numRead)
{
break;
}
}
}
if (pos == 0)
{
fileRead.seek(0);
result.add(fileRead.readLine());
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (fileRead != null)
{
try
{
//關閉資源
fileRead.close();
}
catch (Exception e)
{
}
}
}
return result;
}
}