I want to read a file line by line. BufferedReader is much faster than RandomAccessFile or BufferedInputStream. But the problem is that I do not know how many bytes I read. How do I know bytes read (offset)? I tried.
String buffer; int offset = 0; while ((buffer = br.readLine()) != null) offset += buffer.getBytes().length + 1; // 1 is for line separator
I work if the file is small. But, when the file becomes large, the offset becomes less than the actual value. How can I get the offset?
BufferedReader - : . Windows \r\n . Unix . BufferedReader , , readLine() , .
BufferedReader
\r\n
readLine()
buffer.getBytes() , . byte[] ↔ String , , .
buffer.getBytes()
byte[]
String
InputStream, . , , 5 , InputStream 4096, , .
InputStream
NIO. ByteBuffer , CharBuffer .
ByteBuffer
CharBuffer
, , , int .
, :
import java.io.*; class FileRead { public static void main(String args[]) { try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream("textfile.txt"); // Use DataInputStream to read binary NOT text. BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); String strLine; //Read File Line By Line while ((strLine = br.readLine()) != null) { // Print the content on the console System.out.println (strLine); } //Close the input stream in.close(); }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } } }
, !
: