Link to home
Start Free TrialLog in
Avatar of jerntat
jerntat

asked on

Efficiency in using File object and RandomAccessFile Object

I have 2 piece of code that reads in data from a text file.One of them uses a File Object and the other uses RandomFileAccess as follows:



(1)File Object code:

filename = "c:\\data.dat";

File loaddata = new File(filename)

try
{
    if ( !userdefinefile.exists())
    {
     return;
    }
    else
    {
     BufferedReader br = new BufferedReader(new FileReader(userdefinefile));
                   
        while ( br.readLine() != null)
     {          
            //code to process each line until end of file
        }
         

}catch (Exception ex) {}




(2)RandomAccessFile object code:

filename = "c:\\data.dat"

try
{
    RandomAccessFile loaddata = new RandomAccessFile(filename, "rw");

    while( loaddata.readLine() != null)
    {
        //code to process each line read.
    }
}
catch( Exception ex ){}




The problem is that the code using the RandomAccessFile object seem to be slower that the code using File Object
.Can anybody tell why this is so? And how can I improve the efficiency of using RandomAccessFile Object readLin() method?
Avatar of tonus
tonus

Is it because of RandomAccessFile traffics in bytes rather than characters.
Again you can read the entire file at one stratch using RAF


Here is the code

  RandomAccessFile loaddata = new RandomAccessFile(filename, "rw");

  Byte[] byteArray = new Byte[(int)loaddata.length()];

loaddata.readFully(byteArray);
Avatar of jerntat

ASKER

but you are still reading in the same amount of data whether in byte or chracters,shouldnt both method at least uses the same amount of time

I only wanted to read a small part of the file at a time because i dont want to use too much memory.
ASKER CERTIFIED SOLUTION
Avatar of dnoelpp
dnoelpp
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jerntat

ASKER

Sorry for late reply, but thanks alot for your help, they are very helpful