2

I want to print from a file a specific line, for example the fourth line or the second line. This is my code and it only displays all lines and each lines number. I'm sorry if this is a simple and stupid question, but thank you in advance :D.

FileReader fr = null;
      LineNumberReader lnr = null;
      String str;
      int i;

      try{
         // create new reader
         fr = new FileReader("test.txt");
         lnr = new LineNumberReader(fr);

         // read lines till the end of the stream
         while((str=lnr.readLine())!=null)
         {

            i=lnr.getLineNumber();
            System.out.print("("+i+")");

            // prints string
            System.out.println(str);
             }

      }catch(Exception e){

         // if any error occurs
         e.printStackTrace();
      }finally{

         // closes the stream and releases system resources
         if(fr!=null)
            fr.close();
         if(lnr!=null)
            lnr.close();
      }
   }
}
1

4 Answers 4

2

The easiest way is to simply keep track of which line you're reading. It looks like you want to use i for that. Don't forget to break out of the loop once you've read the line you want.

Also, the continue statement says "skip everything else and move to the next iteration".

See The while and do-while Statements

     while((str=lnr.readLine())!=null)
     {
        i=lnr.getLineNumber();
        if(i != 57) continue;
        System.out.print("("+i+")");

        // prints string
        System.out.println(str);
        break;
     }

Keep in mind that, as the comment below mentioned, LineNumberReader begins reading at 0. So, this would actually return line 56 in natural ordering. If you want 57 in natural ordering, you can use this conditional statement instead. if(i <= 57) continue;

Sign up to request clarification or add additional context in comments.

3 Comments

I think that the variable i is already supposed to hold the line number.
Note, that the line numbering begins at 0 by default. It means if you need exactly 3 line in natural order, IF statement should be if (i != 2) continue;
Thanks, I've added a note about natural ordering.
1

how about

if(i == 2){
    System.out.println(str);
    break;
}

instead of 2 you can give the number in as a commandline argument or user-input.

1 Comment

Don't forget to add break; after it met the required condition.
0

Put some counter inside loop and add aditional condition to while loop e.g counter < 4. I think it should work as you want to.

Comments

0

How about this.

public static void main(String[] args) 
{
    int lineNo = 2;     // Sample line number
    System.out.println("content present in the given line no "+lineNo+" --> "+getLineContents(lineNo));
}

public static String getContents(int line_no) {

     String line = null;

      try(LineNumberReader  lineNumberReader = new LineNumberReader(new FileReader("path\\to\\file")))
      {
        while ((line = lineNumberReader.readLine()) != null) {
            if (lineNumberReader.getLineNumber() == line_no)  {  
                break;
            }
        }                       
      }
      catch(Exception exception){
          System.out.println("Exception :: "+exception.getMessage());
      }
      finally{
          return line;
      }
}

With the help of try-with-resources statement you can avoid closing stream explicitly, everything takes care by them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.