October 10th, 2013, 08:42 PM
Reading a Text File in Java
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.
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?
October 11th, 2013, 02:40 AM
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.