//Java使用FileReader(file)、readLine()讀取文件,以行爲單位,一次讀一行,一直讀到null時結束,每讀一行都顯示行號。
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) {
e1.printStackTrace();
}
}
}io
}file