Java – Read text file from position in Java

iojavatext

I need to read char[] (size is COUNT) from text file from OFFSET with specified Charset. COUNT and OFFSET are in characters, not in bytes.
He is my code:

raf = new RandomAccessFile(filePath, "r");      
if ((mBuffer == null) || (mBuffer.length < count)) {
    mBuffer = new byte[(int)(count/mDecoder.averageCharsPerByte())];
    mByteWrap = ByteBuffer.wrap(mBuffer);
    mCharBuffer = new char[count];
    mCharWrap = CharBuffer.wrap(mCharBuffer);
}
try {
    offset = (int)(offset/mDecoder.averageCharsPerByte());
    count = (int)(count/mDecoder.averageCharsPerByte());
    raf.seek(offset);
    raf.read(mBuffer,0,count);
    mByteWrap.position(0);
    mCharWrap.position(0);
    mDecoder.decode(mByteWrap, mCharWrap, true);
} catch (IOException e) {
    return null;
}
return mCharBuffer;

Is there any way easier ? (without manual matching char->byte)

I was looking about java.util.Scanner, but it's Iterator-style, and i need random access-style.

PS data should'n be copied many times

Best Solution

Use BufferedReader's skip() method. In your case:

BufferedReader reader = new BufferedReader(new FileReader(filePath));
reader.skip(n); // chars to skip
// .. and here you can start reading

And if you want specify a particular encoding you can use

InputStream is = new FileInputStream(filePath);
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
reader.skip(n); // chars to skip
// .. and here you can start reading