1

我正在使用以下代码读取文本文件的前 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);
            }

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

4

3 回答 3

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);
}
于 2013-04-25T11:09:51.320 回答
1

将这两行交换

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

所以它是这样的

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

您在第一次打印之前调用了两次读取。

于 2013-04-25T11:09:31.243 回答
1

在第 9 行,您阅读第一行。这永远不会打印,因为您在打印之前阅读了 while 循环中的第二行

于 2013-04-25T11:09:38.710 回答