#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    2
    Rep Power
    0

    Reading a Text File in Java


    Background:
    I have string data stored in a text file. Each line in the text file is new record. Using Java's BufferedReader(), I can successfully retrieve the first line of data (record 1) or the entire text file using a while loop (all records) and even small groups of records using a for loop.

    My question:
    What code would I write to get the data from say line 12 for instance? I would like to be able to retrieve the data by line number, retrieving just the one record for that line number in the text file. Any ideas?
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2013
    Location
    Saint-Petersburg, Russia
    Posts
    236
    Rep Power
    28
    File is the data storage with sequential access, it does not allow random access at specific point as array do.

    So you need to skip first 11 lines and read 12-th.

    Of course you can write any wrapper which will skip given number of lines so that user will not see this functionality - but this does not change the matter.

    There really is RandomAccessFile in java, however it will not help you much for two reasons:
    - your file is text, not binary - and you do not know where (from which offset) to seek for 12-th line;
    - as a matter of fact in many file system files are sequential in its core so on physical level this will not change the matter greatly.

    Strictly speaking it is not the question of java itself since files are provided by operating system.

IMN logo majestic logo threadwatch logo seochat tools logo