Java使用FileReader(file)、readLine()读取文件,以行为单位,一次读一行,一直读到null时结束,每读一行都显示行号。
01 | public static void readFileByLines(String fileName) { |
02 | File file = new File(fileName); |
03 | BufferedReader reader = null; |
04 | try { |
05 | System.out.println("以行为单位读取文件内容,一次读一行"); |
06 | reader = new BufferedReader(new FileReader(file)); |
07 | String tempString = null; |
08 | int line = 1; |
09 | //一次读一行,读入null时文件结束 |
10 | while ((tempString = reader.readLine()) != null) { |
11 | //把当前行号显示出来 |
12 | System.out.println("line " + line + ": " + tempString); |
13 | line++; |
14 | } |
15 | reader.close(); |
16 | } catch (IOException e) { |
17 | e.printStackTrace(); |
18 | } finally { |
19 | if (reader != null) { |
20 | try { |
21 | reader.close(); |
22 | } catch (IOException e1) { |
23 | } |
24 | } |
25 | } |
26 | } |
594

被折叠的 条评论
为什么被折叠?



