How to read last 5 lines of a .txt file into java

后端 未结 9 1659
长发绾君心
长发绾君心 2020-12-15 03:03

I have a text file that consists of several entries such as:

hello
there
my
name
is
JoeBloggs

How would I read the last five entries in des

9条回答
  •  再見小時候
    2020-12-15 03:36

    we can use MemoryMappedFile for printing last 5 lines:

    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 to print last 5 lines:

    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;
                    }
                }
    
            }
        }
    

提交回复
热议问题