正确地在while循环中使用BufferedReader.readLine()

时间:2012-11-15 20:40:24

标签: java bufferedreader

所以我在将一个文本文件读入我的程序时遇到了问题。这是代码:

     try{
        InputStream fis=new FileInputStream(targetsFile);
        BufferedReader br=new BufferedReader(new InputStreamReader(fis));

        //while(br.readLine()!=null){
        for(int i=0;i<100;i++){
            String[] words=br.readLine().split(" ");
            int targetX=Integer.parseInt(words[0]);
            int targetY=Integer.parseInt(words[1]);
            int targetW=Integer.parseInt(words[2]);
            int targetH=Integer.parseInt(words[3]);
            int targetHits=Integer.parseInt(words[4]);
            Target a=new Target(targetX, targetY, targetW, targetH, targetHits);
            targets.add(a);
        }
        br.close();
    }
    catch(Exception e){
        System.err.println("Error: Target File Cannot Be Read");
    }

我正在阅读的文件是100行参数。如果我使用for循环它完美地工作。如果我使用while语句(for循环上面注释掉的那个),它会在50处停止。用户可能会运行带有任意行数的文件的程序,因此我当前的for循环实现赢了工作。

为什么第while(br.readLine()!=null)行停在50?我检查了文本文件,没有任何东西可以挂起来。

当我使用while循环时,我没有从try-catch中得到任何错误,所以我很难过。有人有什么想法吗?

7 个答案:

答案 0 :(得分:34)

也非常全面......

try{
    InputStream fis=new FileInputStream(targetsFile);
    BufferedReader br=new BufferedReader(new InputStreamReader(fis));

    for (String line = br.readLine(); line != null; line = br.readLine()) {
       System.out.println(line);
    }

    br.close();
}
catch(Exception e){
    System.err.println("Error: Target File Cannot Be Read");
}

答案 1 :(得分:26)

你在循环中第二次打电话给br.readLine() 因此,每次绕行时,最终都会读取两行行。

答案 2 :(得分:10)

您可以使用以下结构:

 while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }

答案 3 :(得分:5)

如果你仍然在绊倒这个问题。 现在,使用Java 8,事情看起来更好:

try {
  Files.lines(Paths.get(targetsFile)).forEach(
    s -> {
      System.out.println(s);
      // do more stuff with s
    }
  );
} catch (IOException exc) {
  exc.printStackTrace();
}

答案 4 :(得分:3)

感谢SLaks和jpm的帮助。这是一个非常简单的错误,我根本没有看到。

正如SLaks所指出的那样,每个循环都会调用br.readLine()两次,这使得程序只获得了一半的值。这是固定代码:

try{
        InputStream fis=new FileInputStream(targetsFile);
        BufferedReader br=new BufferedReader(new InputStreamReader(fis));
        String words[]=new String[5];
        String line=null;
        while((line=br.readLine())!=null){
            words=line.split(" ");
            int targetX=Integer.parseInt(words[0]);
            int targetY=Integer.parseInt(words[1]);
            int targetW=Integer.parseInt(words[2]);
            int targetH=Integer.parseInt(words[3]);
            int targetHits=Integer.parseInt(words[4]);
            Target a=new Target(targetX, targetY, targetW, targetH, targetHits);
            targets.add(a);
        }
        br.close();
    }
    catch(Exception e){
        System.err.println("Error: Target File Cannot Be Read");
    }

再次感谢!你们真棒!

答案 5 :(得分:1)

Concept Solution:br.read() returns particular character's int value so loop 
continue's until we won't get -1 as int value and Hence up to there it print 
br.eadline() which returns a line into String form.
Way 1:
while(br.read()!=-1)
 {
  //continues loop until we won't get int value as a -1
  System.out.println(br.readLine());
 }
 Way 2:
 while((line=br.readLine())!=null)
 {
  System.out.println(line);
 }
 Way 3:
 for(String line=br.readLine();line!=null;line=br.readLine())
 {
  System.out.println(line);
 }``
 Way 4:
 It's an advance way to read file using collection and arrays concept 
 How we iterate using for each loop.

在这里查看 http://www.java67.com/2016/01/how-to-use-foreach-method-in-java-8-examples.html

答案 6 :(得分:1)

除了@ramin给出的答案外,如果您已经拥有BufferedReaderInputStream,还可以通过以下代码进行迭代:

reader.lines().forEach(line -> {
    //...
});

或者如果您需要按照给定的顺序进行处理:

reader.lines().forEachOrdered(line -> {
    //...
});
相关问题