3

我可以使用 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 使用这样的东西,并且读取大量行会更快吗?

4

1 回答 1

-1

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();
}
于 2014-01-21T14:24:33.503 回答