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

时间:2010-03-08 07:56:54

标签: java file position java.util.scanner

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

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

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

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

3 个答案:

答案 0 :(得分:4)

可以使用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();
    }

}

答案 1 :(得分:2)

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

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

答案 2 :(得分:1)

您可以使用自定义FileInputStream创建扫描程序来获取大致的文件位置,如下所示:

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的实现。这对于在文件解析期间更新进度条等内容非常有用 你不需要确切的位置,只需要合理的接近。