Results 1 to 3 of 3
  1. #1
    skaterboy987 is offline Member
    Join Date
    Sep 2011
    Posts
    56
    Rep Power
    0

    Default Read a specific line or a .txt

    I know how to read all lines:
    [CODE]
    import java.io.*;
    class ReadFile
    {
    public static void main(String args[])
    {
    try{
    FileInputStream fstream = new FileInputStream("C:\\Users\\Willy\\Desktop\\Auto Generated\\Test.txt");
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    while ((strLine = br.readLine()) != null) {
    System.out.println (strLine);
    }
    in.close();
    }catch (Exception e){//Catch exception if any
    }
    }
    } [CODE]

    But how could I read...a specific line
    Like line 3;
    or line 1;

  2. #2
    DiamondSoul is offline Member
    Join Date
    Oct 2011
    Posts
    83
    Rep Power
    0

    Default Re: Read a specific line or a .txt

    You have to just read up to that line (i.e. read all the lines before it). I'm 99% sure there is a way to "seek" to a specific offset in a file (though I don't know what that way is off the top of my head; I'd have to look it up), but that would only work to read a specific line if you knew the exact length of all the lines that preceded it.

  3. #3
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default Re: Read a specific line or a .txt

    It depends upon the situation.

    If you simply want to read a specific line N once and nothing else then read n - 1 lines (throw them away) then read and keep the next line.

    If you want to read multiple lines in random order then it would be better if you read the entire file into a List then you can access any line you want by using the line number as an index into the List.

Similar Threads

  1. Replies: 16
    Last Post: 09-17-2011, 02:41 AM
  2. Replies: 3
    Last Post: 06-26-2011, 11:00 AM
  3. Replies: 1
    Last Post: 02-13-2011, 03:09 PM
  4. read a specific line in an input file
    By sara12345 in forum Advanced Java
    Replies: 7
    Last Post: 01-03-2010, 10:40 PM
  5. Replies: 4
    Last Post: 09-10-2009, 10:18 AM

Posting Permissions

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