Using BufferedReader.readLine() in a while loop properly

后端 未结 7 1626
无人共我
无人共我 2020-11-27 19:35

So I\'m having an issue reading a text file into my program. Here is the code:

     try{
        InputStream fis=new FileInputStream(targetsFile);
        Bu         


        
7条回答
  •  北海茫月
    2020-11-27 20:10

    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 prints br.readLine() 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. check it here http://www.java67.com/2016/01/how-to-use-foreach-method-in-java-8-examples.html

提交回复
热议问题