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/compute 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,
The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.
txt is read by FileReader class. The readLine() method of BufferedReader class reads file line by line, and each line appended to StringBuffer, followed by a linefeed. The content of the StringBuffer are then output to the console.
Note: There are many available classes in the Java API that can be used to read and write files in Java: FileReader, BufferedReader, Files, Scanner, FileInputStream, FileWriter, BufferedWriter, FileOutputStream , etc.
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();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With