開發中難免遇到一些需要臨時處理的問題, 比如產品經理給到你一個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 才可以這樣寫