开发中难免遇到一些需要临时处理的问题, 比如产品经理给到你一个TXT文件,帮我把这个数据 怎么怎么样...很急 现在就要
当然这种事情也是见怪不怪
读取文件的代码其实平时用的比较少,因为都是在开发业务逻辑 和数据库打交道
今天就来复习一下:
要读取一个文本文件,步骤:
1. 先获得文件句柄. 根据文件的路径创建一个File对象
2.有了文件当然需要转化流进行读
3.使用 reader 读取流信息
4.读取reader的每一个行即可
具体代码:
public static void readTxtFile(String filePath) {
File file = new File(filePath);
String encoding = "utf-8";
try (InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
BufferedReader bufferedReader = new BufferedReader(read)) {
//判断文件是否存在
if (file.isFile() && file.exists()) {
String lineTxt;
while ((lineTxt = bufferedReader.readLine()) != null) {
System.out.println(lineTxt);
}
} else {
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
}
}
拓展
try(){
}
代码中用到了try()语法
其中 ()里面的流 和reader 会自动关闭 无需手动关闭,但是()的对象或其父类必须 implements Closeable 才可以这样写