次のように、カスタム FileInputStream を使用して Scanner を作成することにより、おおよそのファイル位置を取得できます。
final int [] aiPos = new int [1];
FileInputStream fileinputstream = new FileInputStream( file ) {
@Override
public int read() throws IOException {
aiPos[0]++;
return super.read();
}
@Override
public int read( byte [] b ) throws IOException {
int iN = super.read( b );
aiPos[0] += iN;
return iN;
}
@Override
public int read( byte [] b, int off, int len ) throws IOException {
int iN = super.read( b, off, len );
aiPos[0] += iN;
return iN;
}
};
Scanner scanner = new Scanner( fileinputstream );
これにより、FileInputStream の実装に応じて、8K 程度の正確な位置が得られます。これは、ファイルの解析中にプログレス バーを更新する場合など、正確な位置を必要とせず、適度に近い位置にある場合に役立ちます。