Results 1 to 8 of 8
  1. #1
    sara12345 is offline Member
    Join Date
    Dec 2009
    Posts
    59
    Rep Power
    0

    Default read a specific line in an input file

    hello every one
    how can I read a specific line in java for example line 7 in an input file I have used buffered reader but in this method I need to used line.nexline() and also I have used the LinenumberReader but in this method I can not give the line number I want to read

    please help
    thanks alot

  2. #2
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,234
    Rep Power
    7

    Default

    In general you can't read the 7th line directlly. You need to create a loop to read the first 6 first.

    However, if the length of each line is a "fixed length", then you can use RandomAccessFile and calculate the bytes to read manually at one time. I doubt you lines are fixed length so you will need to use the first solution.

  3. #3
    travishein's Avatar
    travishein is offline Senior Member
    Join Date
    Sep 2009
    Location
    Canada
    Posts
    684
    Rep Power
    5

    Default

    You would need to read the lines before this line, and just ignore them or discard them, and for each line read, increment a counter, when the counter reaches the desired line, return that line, and of course checking to see if the file runs out before the requested line number has come up.


    Java Code:
      /**
       * Reads a specific line from a text file in a platform neutral way, ignoring the lines before, and stopping after
       * reaching the desired line.
       * 
       * @param file
       *          The file to read from
       * @param lineNumber
       *          the line number to read.
       * @return the line that was requested, or null if the line number requested exceeds the number of lines in the file.
       * @throws IOException
       *           if an error was encountered while trying to read the file
       */
      public static String readSpecificLine(File file, int lineNumber) throws IOException {
        StringBuilder lineBuffer = new StringBuilder();
        String result = null;
        int lineCount = 0; // used to read until the specific line has been found.
        Reader reader = new InputStreamReader(new FileInputStream(file));
        try {
          char[] buffer = new char[4096];
    
          outer: for (int charsRead = reader.read(buffer); charsRead >= 0; charsRead = reader.read(buffer)) {
            for (int charIndex = 0; charIndex < charsRead; charIndex++) {
              char aChar = buffer[charIndex];
              switch (aChar) {
                case '\r': // ignore DOS end of lines (that will be before \n)
                  break;
                case '\n':
                  lineCount++;
                  if (lineCount == lineNumber) {
                    result = lineBuffer.toString();
                    break outer;
                  }
                  else {
                    // read a new line, but not interested in this line, discard
                    lineBuffer = new StringBuilder();
                  }
                  break;
                default:
                  lineBuffer.append(aChar);
                  break;
              } // switch
            } // for (lineCount)
          } // for ( reading the file )
        }
        finally {
          try {
            reader.close();
          }
          catch (IOException ex) {
            // empty
          }
        }
        return result;
      }
    I used this post on sun forums to read a new line in a platform independent manner:

    Java Programming [Archive] - Fastest way to line count a file

  4. #4
    sara12345 is offline Member
    Join Date
    Dec 2009
    Posts
    59
    Rep Power
    0

    Default

    thanks alot for the replies I though that there is a way to read a line directly but now I have used line.nextLine() to go to specific line
    thanks alot

  5. #5
    raqman is offline Member
    Join Date
    Sep 2009
    Posts
    37
    Rep Power
    0

    Default

    http://java.sun.com/javase/6/docs/ap...l/Scanner.html can be used for scanning and processing many kinds of text input from a variety of sources.

    http://java.sun.com/javase/6/docs/ap...redReader.html allows for buffered reading from an input stream and has a readLine() method that will read a single line from a stream (file in your case).

    String.split() http://java.sun.com/javase/6/docs/ap...va.lang.String) splits a string by the supplied expression and returns the pieces as an array of strings.

    The following code fragment opens a BufferedReader against a text file and reads each line.
    Help with Code Tags Java Syntax (Toggle Plain Text)
    try { BufferedReader reader = new BufferedReader(new FileReader("file.txt")); String line = null; while ((line = reader.readLine()) != null){ System.out.println(line); } } catch (Exception e){ e.printStackTrace(); } try {
    BufferedReader reader = new BufferedReader(new FileReader("<strong class="highlight">file</strong>.txt"));

    String <strong class="highlight">line</strong> = null;
    while ((<strong class="highlight">line</strong> = reader.readLine()) != null){
    System.out.println(<strong class="highlight">line</strong>);
    }
    } catch (Exception e){
    e.printStackTrace();
    }
    With that as a starting point, see if you can get the elements into your array and post back if you run into problems.
    RAQ Report: free Java reporting tool.

  6. #6
    masternerdguy is offline Member
    Join Date
    Jan 2010
    Posts
    9
    Rep Power
    0

    Default

    An idea is to load the entire file as a string and split the file by the linebreak character. Then just take the array[6] (the 6th index of the array) and you can access that line only.

  7. #7
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,435
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by masternerdguy View Post
    An idea is to load the entire file as a string and split the file by the linebreak character. Then just take the array[6] (the 6th index of the array) and you can access that line only.
    Cute if your file has a zillion lines and you only need line number six.

    kind regards,

    Jos

  8. #8
    Supamagier is offline Senior Member
    Join Date
    Aug 2008
    Posts
    384
    Rep Power
    6

    Default

    Quote Originally Posted by masternerdguy View Post
    An idea is to load the entire file as a string and split the file by the linebreak character. Then just take the array[6] (the 6th index of the array) and you can access that line only.
    What the other guy said. :) Besides, array[6] is the 7th index (A)
    I die a little on the inside...
    Every time I get shot.

Similar Threads

  1. Replies: 4
    Last Post: 09-10-2009, 10:18 AM
  2. writing to specific line in text file
    By mickmos in forum New To Java
    Replies: 2
    Last Post: 04-18-2009, 01:01 PM
  3. Writing To A Specific Text File Line
    By mokonji in forum New To Java
    Replies: 1
    Last Post: 03-02-2009, 08:13 PM
  4. Reading data from csv file based on specific input
    By jaiminparikh in forum Advanced Java
    Replies: 14
    Last Post: 02-13-2009, 09:07 PM
  5. read the file from different line number
    By vaskarbasak in forum Advanced Java
    Replies: 3
    Last Post: 06-02-2008, 01:31 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •