使用SeekableByteChannel从文件中读取行

时间:2013-10-11 22:16:37

标签: java

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

1 个答案:

答案 0 :(得分:-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();
}
相关问题