gpt4 book ai didi

java - 使用 SeekableByteChannel 从文件中读取行

转载 作者:行者123 更新时间:2023-12-02 09:16:00 25 4
gpt4 key购买 nike

我可以使用 SeekableByteChannel 从文件中读取行吗?我有位置(以字节为单位)并且想要读取整行。例如我将此方法用于 RandomAccessFile

private static String currentLine(String filepath, long currentPosition)
{
RandomAccessFile f = new RandomAccessFile(filepath, "rw");

byte b = f.readByte();
while (b != 10)
{
currentPosition -= 1;
f.seek(currentPosition);
b = f.readByte();
if (currentPosition <= 0)
{
f.seek(0);
String currentLine = f.readLine();
f.close();
return currentLine;
}
}
String line = f.readLine();
f.close();
return line;

}

我如何将这样的东西用于SeekableByteChannel,并且读取大量行会更快吗?

最佳答案

我正在使用 SeekableByteChannel 读取大文件,例如 3gb,并且效果很好...

try {
Path path = Paths.get("/home/temp/", "hugefile.txt");
SeekableByteChannel sbc = Files.newByteChannel(path,
StandardOpenOption.READ);
ByteBuffer bf = ByteBuffer.allocate(941);// line size
int i = 0;
while ((i = sbc.read(bf)) > 0) {
bf.flip();
System.out.println(new String(bf.array()));
bf.clear();
}
} catch (Exception e) {
e.printStackTrace();
}

关于java - 使用 SeekableByteChannel 从文件中读取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19328108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com