java一行一行讀入資料
阿新 • • 發佈:2019-02-18
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException ; public class txt { public static void readFileByLines(String fileName) { File file = new File(fileName); BufferedReader reader = null; try { System.out.println("以行為單位讀取檔案內容,一次讀一行"); reader = new BufferedReader(new FileReader(file)); String tempString = null; int line = 1; //一次讀一行,讀入null時檔案結束 while ((tempString = reader.readLine()) != null) { //把當前行號顯示出來 System.out.println("line " + line + ": " + tempString); line++; } reader.close(); } catch(IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } } public static void main(String argv[]) { String filePath = "f:TOTAL.txt"; readFileByLines(filePath); } }