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 );

这将为您提供精确到 8K 左右的位置,具体取决于 FileInputStream 的实现。这对于在文件解析期间更新进度条之类的事情很有用,您不需要确切的位置,只需要相当接近的位置。

于 2010-05-12T15:53:25.617 回答