如何将.txt文件的最后5行读入java

我有一个文本文件,包含几个条目,如:

hello there my name is JoeBloggs 

我如何按降序读取最后五个条目,即来自JoeBloggs-那里

我目前只有代码才能阅读最后一行:

 public class TestLastLineRead { public static void main(String[] args) throws Exception { FileInputStream in = new FileInputStream(file.txt); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = null, tmp; while ((tmp = br.readLine()) != null) { strLine = tmp; } String lastLine = strLine; System.out.println(lastLine); in.close(); } } 

您可以将行添加到List ,例如LinkedList 。 当列表超过五行时,删除第一个/最后一个。

 List lines = new LinkedList(); for(String tmp; (tmp = br.readLine()) != null;) if (lines.add(tmp) && lines.size() > 5) lines.remove(0); 

一种非常简单的方法是使用Apache Commons Collections库中的CircularFifoBuffer类。 它基本上是一个固定大小的列表,它会在旧元素已满时丢弃旧元素并添加新元素。 因此,您将创建一个大小为5的CircularFifoBuffer ,然后将所有行添加到其中。 最后,它只包含文件的最后五行。

我们可以使用MemoryMappedFile打印最后5行:

 private static void printByMemoryMappedFile(File file) throws FileNotFoundException, IOException{ FileInputStream fileInputStream=new FileInputStream(file); FileChannel channel=fileInputStream.getChannel(); ByteBuffer buffer=channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()); buffer.position((int)channel.size()); int count=0; StringBuilder builder=new StringBuilder(); for(long i=channel.size()-1;i>=0;i--){ char c=(char)buffer.get((int)i); builder.append(c); if(c=='\n'){ if(count==5)break; count++; builder.reverse(); System.out.println(builder.toString()); builder=null; builder=new StringBuilder(); } } channel.close(); } 

RandomAccessFile打印最后5行:

 private static void printByRandomAcessFile(File file) throws FileNotFoundException, IOException{ RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); int lines = 0; StringBuilder builder = new StringBuilder(); long length = file.length(); length--; randomAccessFile.seek(length); for(long seek = length; seek >= 0; --seek){ randomAccessFile.seek(seek); char c = (char)randomAccessFile.read(); builder.append(c); if(c == '\n'){ builder = builder.reverse(); System.out.println(builder.toString()); lines++; builder = null; builder = new StringBuilder(); if (lines == 5){ break; } } } } 

尝试这段代码,通过所有行扫描长度为5的列表,最后列表被反转。 我编辑/修改了你的代码,测试它以确保它完全正常工作。

 import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; public class Test { public static void main(String[] args) throws Exception { ArrayList bandWidth = new ArrayList(); FileInputStream in = new FileInputStream("file.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String tmp; while ((tmp = br.readLine()) != null) { bandWidth.add(tmp); if (bandWidth.size() == 6) bandWidth.remove(0); } ArrayList reversedFive = new ArrayList(); for (int i = bandWidth.size() - 1; i >= 0; i--) reversedFive.add(bandWidth.get(i)); in.close(); } } 

如果真的要做的就是打印最后5行:

  ArrayList lines = new ArrayList(); String tmp=""; while ((tmp = br.readLine()) != null) { lines.add(tmp); } for (int i = lines.size()-5; i < lines.size(); i++) { System.out.println(lines.get(i-1)); } 

首先,您必须逐行读取文件并将每行添加到列表中。 完全读取文件后,您可以按相反的顺序打印列表中的每个元素,如下所示:

 import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class FileReader { public static List readFile() throws IOException { List fileContents = new ArrayList(); FileInputStream fileInputStream = new FileInputStream("C:/Users/compaq/Desktop/file.txt"); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String strLine = null; while((strLine=bufferedReader.readLine())!=null) { fileContents.add(strLine); } fileInputStream.close(); return fileContents; } public static void printFileInReverse(List fileContents, int numberOfLines) { int counter = 0; for(int i=(fileContents.size()-1);i>=0;i--) { if(counter==numberOfLines) { break; } System.out.println(fileContents.get(i)); counter++; } } public static void main(String[] args) throws IOException { List fileContents = new ArrayList(); fileContents = FileReader.readFile(); int numberOfLines = 5;// Number of lines that you would like to print from the bottom of your text file. FileReader.printFileInReverse(fileContents, numberOfLines); } } 

尝试这个。 这给出了最后5行。

  public static void main(String[] args) throws IOException { List list =new ArrayList(); FileInputStream in = new FileInputStream("C:/adminconsole.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine ="", tmp; while ((tmp = br.readLine()) != null){ //strLine =tmp+"\n"+strLine; list.add(tmp); } if(list.size()>5){ for (int i=list.size()-1; i>=(list.size()-5); i--) { System.out.println(list.get(i)); } }else{ for (int i=0; i<5; i++) { System.out.println(list.get(i)); } } } } 

遵循此代码通过使用Collectios改进核心Java逻辑。

 import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Scanner; public class REVERSE { public static void main(String[] args) { ArrayList al = new ArrayList(); try { Scanner sc = new Scanner(new FileReader("input.txt")); while (sc.hasNextLine()) { al.add(sc.nextLine()); } System.out.println(al.get(0)); System.out.println(al.get(1)); System.out.println(al.get(2)); System.out.println(al.get(3)); System.out.println(al.get(4)); Collections.reverse(al); /* * for (String s : al) { System.out.println(s); } */ System.out.println(al.get(0)); System.out.println(al.get(1)); System.out.println(al.get(2)); System.out.println(al.get(3)); System.out.println(al.get(4)); /* * for (int i = 0; i < al.size(); i++) { * System.out.println(al.get(i)); } */ } catch (FileNotFoundException e) { } } } 

请试试这段代码。 它对我来说很好。

 public static void main(String[] args) { try { int numOfLastline = 10; BufferedReader reader = new BufferedReader(new FileReader("Text.txt")); int lines = 0; while (reader.readLine() != null) lines++; reader.close(); System.out.println(lines); String printedLine = null; List listForString = new ArrayList(); for (int i = lines - 1; i >= (lines - numOfLastline); i--) { printedLine = (String) FileUtils.readLines(new File("Text.txt"), "ISO-8859-1").get(i); System.out.println(printedLine); listForString.add(printedLine); } System.out.println("\n\n============ Printing in Correct order =============\n\n"); Collections.reverse(listForString); for (int k = 0; k < listForString.size() ; k++) { System.out.println(listForString.get(k)); } } catch (Exception e) { e.printStackTrace(); } } 

注意:在numOfLastline和file [而不是此Text.txt ]中提供所需的最后一个行号。