faiz fz
faiz fz

Reputation: 41

Efficient way to read specific lines in a file other than Random Access File - Java

I want to efficiently read specific lines of a file in Java.

As of now, I have been using the method public int read(byte[] b) from the class Random access file. Its fast, but is there any other technique which is much faster.

The file has around 200,000+ lines. I have collected offsets and length of each line. I use this in read(byte) method. I usually have to read around 1-75000 specific lines. It takes more than 50s for this. Is it possible to optimise this?

            RandomAccessFile dicti = new RandomAccessFile(file,"r");
            for(int i:totalLines){
            Long start = getOffset(ID);
            dicti.seek(start);  
            byte[] bytes = new byte[lengthinBytesfortheLine(i)];
            dicti.read(bytes);
            line =new String(bytes);}

Upvotes: 3

Views: 228

Answers (1)

Sambit
Sambit

Reputation: 8011

You can read line by line and perform some manipulation. I provide below the example.

try (Stream<String> stream = Files.lines(Paths.get(yourFileName))) {

            stream.forEach( line -> performSomeOperation(line));

        } catch (Exception e) {
            e.printStackTrace();
        }

performSomeOperation(String line) is a method where you can do some operation based upon the need.

Upvotes: 1

Related Questions