最近看到文件操作,偶然看到在读取的过程中略有不同,遂在这里简单的来解析下两种方法的不同之处:
其一:
这是在网上普遍看到的方法,来说下while中的条件,lineTxt为读取到的内容的承载对象字符串,bufferedReader.readLine()为整行读取内容,系统规定,当读取到流末尾后返回null,退出while循环。这里关闭文件是在读取结束后就执行的,博主认为不太妥当。
//效率高
public void readTxtFile(String filePath) {
try {
File file = new File(filePath);
if (file.isFile() && file.exists()) {
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
BufferedReader br = new BufferedReader(isr);
String lineTxt = null;
while ((lineTxt = br.readLine()) != null) {
System.out.println(lineTxt);
}
br.close();
} else {
System.out.println("文件不存在!");
}
} catch (Exception e) {
System.out.println("文件读取错误!");
}
}
其二:
此处while 循环中用字节数判断是否读取结束,fis.read(bytes)表示读取的字节数,文档中表明,当读取不到时返回-1,n为读取到的字节数(也可用字符来代替),还有就是关于try/catch的使用,最后的finally,关闭文件放在这里更合适点。
//效率低
File fl = new File("image/1.txt");
System.out.println(fl.getAbsolutePath());
// 因为file没有读写的能力,所以需要用InputStream
FileInputStream fis = null;
try {
fis = new FileInputStream(fl);
// 定义一个字节数组,相当于缓存
byte[] bytes = new byte[1024];
int n = 0;// 得到实际读取到的字节数
// 循环读取
while ((n = fis.read(bytes)) != -1) {
// 把字节转成string
String s = new String(bytes, 0, n);
System.out.println(s);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 关闭文件,必须放这里
try {
fis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
以上两种写法都可以拿到数据,博主对其中的一些认知有些不同,发出来大家看看,比较推荐第二种写法,原因上面已经给出,还请大家吧甄别。