主要通过BufferedReader的readLine()方法按行读取字符串,如下代码所以
读取完毕后记得关闭文件流,最好统一放在finally中关闭
public void readLine(String path) {
InputStreamReader isr = null;
BufferedReader br = null;
try {
isr = new InputStreamReader(new FileInputStream(path));
br = new BufferedReader(isr);
String str;
// 通过readLine()方法按行读取字符串
while ((str = br.readLine()) != null) {
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 统一在finally中关闭流,防止发生异常的情况下,文件流未能正常关闭
try {
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。