JAvaファイルの最後のN行を読み込む
译文:javaはファイルの最后のN行を読みます
ソースコードのダウンロードアドレス:http://www.zuidaima.com/share/1550463669226496.htm
この行からファイルの最後までのすべての行を取得し、クマから共有できる行数を指定します.
ソースファイル:
最後の10行の結果を読み込む
ソースコードのダウンロードアドレス: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
*/
public static List readLastNLine(File file, long numRead)
{
//
List result = new ArrayList();
//
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);
//
if (fileRead.readByte() == '
')
{
// 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;
}
}