我以下面的方式读取文件的每一行
BufferedReader in = new BufferedReader(new FileReader(inFile)); while (null != (line = in.readLine())) { }
我想在第一行和最后一行单独进行一些验证.有没有
检查它是否是while循环中的第一行和最后一行
while (null != (line = in.readLine())) { if(firstlineoffile) { } else if (lastlineoffile) { } else { } }
解决方法
酷问题我打了一圈,这是一个
@L_502_0@,只是copy’n’paste’n’run它.
package com.stackoverflow.q2292917; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; public class Test { public static void main(String... args) throws IOException { // Create test file. File file = new File("/test.txt"); PrintWriter writer = new PrintWriter(file); writer.println("line 1"); writer.println("line 2"); writer.println("line 3"); writer.println("line 4"); writer.println("line 5"); writer.close(); // Read test file. BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String next,line = reader.readLine(); for (boolean first = true,last = (line == null); !last; first = false,line = next) { last = ((next = reader.readLine()) == null); if (first) { System.out.println("first line: " + line); } else if (last) { System.out.println("last line: " + line); } else { System.out.println("normal line: " + line); } } } finally { if (reader != null) try { reader.close(); } catch (IOException logorIgnore) {} } // Delete test file. file.delete(); } }
输出:
first line: line 1 normal line: line 2 normal line: line 3 normal line: line 4 last line: line 5
但是,我对初学者的可读性和可解释性提出质疑…;)