I have a bit of 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'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();
...
}
I can't figure out how to get/c开发者_Python百科ompute the value for 'position'.
Two things: I don't have obviously a fixed length file (i.e.: every line has a different length) I need to make it work on any system (linux, unix, windows) so I am not sure if I can assume the length of newline (whether it's one or two chars)
Any help very much appreciated.
Thanks,
If you can keep the file opened, you can try with mark()
and reset()
. If you have to close the file and reopen, try FileInputStream.getChannel().position()
and FileInputStream.skip()
I think you should use FileChannel. Example:
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();
}
}
}
精彩评论