java中如何读取文件中最后n个字符?
下文笔者将讲述读取一个文件中最后几个字符的方法分享,如下所示:
在工作中我们经常会遇到这样一个需求,读取文件末尾的多少个字符,这种操作,
那么如何实现此类需求呢?下文将一一道来,如下所示:
在工作中我们经常会遇到这样一个需求,读取文件末尾的多少个字符,这种操作,
那么如何实现此类需求呢?下文将一一道来,如下所示:
实现思路:
可以使用FileChannel类(java.nio.channels.FileChannel)
中的相关方法满足相关需求
例:
package com.java265;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class FileReadLastNCharacters {
public static void main(String[] args) {
Path logPath = Paths.get("C:/opt/logs/20220107.log");
ByteBuffer buffer = ByteBuffer.allocate(1024);
try {
FileChannel channel = FileChannel.open(logPath, StandardOpenOption.READ);
channel.read(buffer, channel.size() - 1000);
System.out.println("Characters = " + new String(buffer.array()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


