如果我用FileReader读取它,我怎么知道我在文件中的位置?

时间:2011-05-19 11:46:31

标签: java

我有一些像这样的代码:

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

我无法弄清楚如何获取/计算'位置'的值。

两件事: 我显然没有固定长度的文件(即:每行有不同的长度) 我需要让它适用于任何系统(linux,unix,windows),所以我不确定我是否可以假设换行的长度(无论是一个还是两个字符)

非常感谢任何帮助。

谢谢,

2 个答案:

答案 0 :(得分:2)

我认为你应该使用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();
    }
}
}

答案 1 :(得分:2)

如果您可以保持文件打开,可以尝试使用mark()reset()。如果您必须关闭该文件并重新打开,请尝试FileInputStream.getChannel().position()FileInputStream.skip()