LineNumberReader跳过文件的第一行

时间:2013-04-25 11:07:31

标签: java readline

我正在使用以下代码阅读文本文件的前6行:

File finish = new File("C:/ABC Statements final/");
        File[] finf = finish.listFiles();
        String[] filenames1 = finish.list();
        LineNumberReader br = null;  
        PrintWriter bw = null;  
        for (int k = 0; k < filenames1.length; k++) {
            try {
            br = new LineNumberReader(new FileReader(new File("C:/ABC Statements final/" + filenames1[k])));  
            String line = br.readLine();  

            while (line != null && br.getLineNumber() <= 6 ) {   
                line = br.readLine();  
                System.err.println(line);
            }  


            } catch (Exception asd) {
                System.err.println(asd);
            }

我的输出不会打印文件的第一行。谁知道我做错了什么?

3 个答案:

答案 0 :(得分:5)

那是因为你吃掉了read的第一行。

String line = br.readLine();  // First line was read here.

while (line != null && br.getLineNumber() <= 6 ) {   
    line = br.readLine();  // Your first line was overriden here.
    System.err.println(line);
}

让您的上述代码看起来像这样: -

String line = null;  
while ((line = br.readLine()) != null && br.getLineNumber() <= 6 ) {   // Line is read and checked - both together
    System.err.println(line);
}

答案 1 :(得分:1)

将这两行换成

line = br.readLine();  
System.err.println(line);

所以就像这样

System.err.println(line);
line = br.readLine(); 

在第一次打印之前,您正在调用两次。

答案 2 :(得分:1)

第9行你读第一行。由于您在打印前读取while循环中的第二行

,因此永远不会打印