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?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With