如何从java扫描仪获取文件中的位置(字节位置)?

5 java position file java.util.scanner

如何从java扫描仪获取文件中的位置(字节位置)?

Scanner scanner = new Scanner(new File("file"));
scanner.useDelimiter("abc");
scanner.hasNext();
String result = scanner.next();
Run Code Online (Sandbox Code Playgroud)

现在:如何获取文件中结果的位置(以字节为单位)?

使用scanner.match().start() 不是答案,因为它给出了内部缓冲区中的位置。

raj*_*raj 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();
    }

}
Run Code Online (Sandbox Code Playgroud)


pol*_*nts 3

Scanner提供对底层的抽象Readable,其内容不一定来自File. 它不直接支持您正在寻找的那种低级查询。

您也许可以通过根据 组合内部缓冲区位置Scanner和根据 读取的字节数来计算这个数字Readable,但即使这看起来也是一个棘手的命题。如果大文件中的大致位置是可以接受的,那么这可能就足够了。