Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading lines from file using SeekableByteChannel

Tags:

java

Can I use SeekableByteChannel for reading lines from file. I have the position (in bytes) and want to read the whole line. for example I use this method for 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;  

}

How can I use something like this for SeekableByteChannel, and will be it faster for reading huge numbers of lines?

like image 201
Aram Kirakosyan Avatar asked Feb 24 '26 10:02

Aram Kirakosyan


1 Answers

I am using SeekableByteChannel to read huge files, like 3gb, and works very well...

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();
}
like image 56
Koike Avatar answered Feb 27 '26 03:02

Koike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!