java中BufferedReader读取文件中有特殊符号的方法

今天被问到一个问题,BufferedReader中的readLine()方法是否是每一次读取文件中一行,所以才要用while,之前一直只知道这样用,还真没去仔细看过源码,毕竟流这块怎么说呢,用的不是很多,而且一般情况也没人会问流的问题。今天工作上遇到就查下,记录一下。

1:BufferedReader是否是一次性吧文件读入内存中,那一个几十兆的文件呢,防止内存溢出

方法就是分块读取,网上例子:

File file =  new  File(filepath);   
BufferedInputStream fis =  new  BufferedInputStream( new  FileInputStream(file));    
BufferedReader reader =  new  BufferedReader( new  InputStreamReader(fis, "utf-8" ), 5 * 1024 * 1024 ); // 用5M的缓冲读取文本文件  
         
String line =  "" ;
while ((line = reader.readLine()) !=  null ){
//TODO: write your business
}
2, readLine()这个方法是一行一行的读,所以打印只能是在while中打印读取的内容

这是工作上解决的一个问题,目的是读取txt文件的时候把里面的特殊符号替换掉,因为特殊符号显示会乱码,而且转码是转不出来的

public static void main1(String[] args) {
String filePath = "d:\\tmp/1517204314673\\c_AssItem_2.txt";
try {
long a = System.currentTimeMillis();
String encoding = "GBK";
File file = new File(filePath);
if (file.isFile() && file.exists()) {
InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
byte[] b = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
b = lineTxt.getBytes();
for (int i = 0; i < b.length; i++) {
if (b[i] == 16) {
// b[i] = 47;
b[i] = 35;
}
if (b[i] == 18) {
// b[i] = 92;
b[i] = 38;
}
}


}
read.close();
System.out.println(new String(b));
long bb = System.currentTimeMillis();
System.out.println(bb - a);
} else {
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}


}

猜你喜欢

转载自blog.csdn.net/hq091117/article/details/79272173