我想逐行阅读文件.BufferedReader比RandomAccessFile或BufferedInputStream快得多.但问题是我不知道我读了多少字节.如何知道字节读取(偏移)?我试过了.
String buffer;
int offset = 0;
while ((buffer = br.readLine()) != null)
offset += buffer.getBytes().length + 1; // 1 is for line separator
Run Code Online (Sandbox Code Playgroud)
如果文件很小,我的工作.但是,当文件变大时,偏移量变得小于实际值.我怎样才能抵消?
BufferedReader
由于两个影响,没有简单的方法可以做到这一点:字符结束和行结尾.在Windows上,行结尾\r\n
是两个字节.在Unix上,行分隔符是单个字节.BufferedReader
将在没有你注意的情况下处理这两种情况,所以之后readLine()
,你将不知道跳过了多少字节.
buffer.getBytes()
当您的默认编码和文件中的数据编码意外碰巧相同时,也只返回正确的结果.使用任何类型的byte[]
< - > String
转换时,应始终准确指定应使用的编码.
您也不能使用计数,InputStream
因为缓冲的读取器以大块读取数据.因此,在读取第一行,例如5个字节后,内部的计数器InputStream
将返回4096,因为读取器总是将多个字节读入其内部缓冲区.
你可以看看NIO吧.您可以使用较低级别ByteBuffer
来跟踪偏移并将其包装在a中CharBuffer
以将输入转换为行.
Gas*_*ret -3
如果您想逐行读取文件,我会推荐以下代码:
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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
我以前一直用这个方法,效果很好!
来源:这里
归档时间: |
|
查看次数: |
4906 次 |
最近记录: |