How to get a position in a file (byte position) from a java scanner?

How to get a position in a file (byte position) from a java scanner?

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

and now: how to get the position of the result in the file (in bytes)?

Using scanner.match (). start () is not the answer as it gives a position in the internal buffer.

+3
source share
3 answers

Its possible to use RandomAccessFile .. try this.

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

}
+4
source

Scannerprovides an abstraction over the base Readable, the contents of which do not have to come from File. It does not support the type of low-level queries you are looking for.

, Scanner , Readable, . , .

+2

, 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. , , , - .

+1

Source: https://habr.com/ru/post/1735878/


All Articles