How do I know where I am in a file if I read it using FileReader?

I have some code like this:

FileReader fr = new FileReader(file);
BufferedReader reader = new BufferedReader(fr);
for (int i=0;i<100;i++) 
{
   String line = reader.readLine(); 
   ...
}

// at this point I would like to know where I am in the file.
// let assign that value to 'position' 
// then I would be able to continue reading the next 100 lies (this could be done later on ofcourse... )
// by simply doing this: 

FileReader fr = new FileReader(file);
fr.skip(position); 
BufferedReader reader = new BufferedReader(fr);
for (int i=0;i<100;i++) 
{
   String line = reader.readLine(); 
   ...
}

I can not figure out how to get / calculate the value for 'position'.

Two things: I don’t have an explicit file with a fixed length (i.e., each line has a different length) I need to get it to work on any system (linux, unix, windows), so I'm not sure if I can read the length of a new line (be it one or two characters)

Any help is greatly appreciated.

Thank,

+5
source share
2 answers

If you can keep the file open, you can try with mark()and reset(). If you need to close the file and open it again, try FileInputStream.getChannel().position()andFileInputStream.skip()

+2
source

, FileChannel. :

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileRead {
    public static void main(String[] args) {
    try {
        String path = "C:\\Temp\\source.txt";
        FileInputStream fis = new FileInputStream(path);
        FileChannel fileChannel = fis.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(64);

        int bytesRead = fileChannel.read(buffer);
        while (bytesRead != -1) {
            System.out.println("Read: " + bytesRead);
            System.out.println("Position: " + fileChannel.position());
            buffer.flip();

            while (buffer.hasRemaining()) {
                System.out.print((char) buffer.get());                    
            }

            buffer.clear();
            bytesRead = fileChannel.read(buffer);
        }

        fis.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}
+2

All Articles