5

Javaスキャナからファイル内の位置(バイト位置)を取得するには?

Scanner scanner = new Scanner(new File("file"));
scanner.useDelimiter("abc");
scanner.hasNext();
String result = scanner.next();

そして今:ファイル内の結果の位置を取得する方法(バイト単位)?

scanner.match().start() を使用することは、内部バッファー内の位置を提供するため、答えではありません。

4

3 に答える 3

5

RandomAccessFile を使用する可能性があります..これを試してください..

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomFileAccessExample 
{
    RandomFileAccessExample() throws IOException
    {
        RandomAccessFile file = new RandomAccessFile("someTxtFile.txt", "r");
        System.out.println(file.getFilePointer());
        file.readLine();
        System.out.println(file.getFilePointer());
    }
    public static void main(String[] args) throws IOException {
        new RandomFileAccessExample();
    }

}
于 2010-03-08T08:33:20.740 に答える
2

Scanner基になる、の抽象化を提供しますReadable。そのコンテンツは必ずしも。からのものである必要はありませんFile。それはあなたが探している種類の低レベルのクエリを直接サポートしていません。

Scannerに従って内部バッファの位置と、に従って読み取られたバイト数を組み合わせることで、この数を計算できる場合がありますがReadable、これでも難しい提案のように見えます。巨大なファイル内のおおよその位置が許容できる場合は、これで十分な場合があります。

于 2010-03-08T08:25:04.210 に答える
1

次のように、カスタム 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 程度の正確な位置が得られます。これは、ファイルの解析中にプログレス バーを更新する場合など、正確な位置を必要とせず、適度に近い位置にある場合に役立ちます。

于 2010-05-12T15:53:25.617 に答える