I was doing some research on IO and I read the following article which talks about buffering techniques. To minimize disk accesses and work by the underlying operating system, buffering techniques use a temporary buffer that reads data in a chunk-wise manner, instead of reading data directly from the disk with every read operation.
Examples were given without and with buffering.
without buffering:
try
{
File f = new File("Test.txt");
FileInputStream fis = new FileInputStream(f);
int b; int ctr = 0;
while((b = fis.read()) != -1)
{
if((char)b== '\t')
{
ctr++;
}
}
fs.close();
// not the ideal way
} catch(Exception e)
{}
With buffering:
try
{
File f = new File("Test.txt");
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bs = new BufferedInputStream(fis);
int b;
int ctr = 0;
while((b =bs.read()) != -1)
{
if((char)b== '\t')
{
ctr++;
}
}
fs.close(); // not the ideal way
}
catch(Exception e){}
The conclusion was:
Test.txt was a 3.5MB file
Scenario 1 executed between 5200 to 5950 milliseconds for 10 test runs
Scenario 2 executed between 40 to 62 milliseconds for 10 test runs.
Is there any other way to do this in Java that is better? Or any other method / technique to give better performance?Please advise..!
In terms of IO performance, that probably is going to be the best without a lot of other code. You are going to be IO bound most likely anyway.
This is very inefficient to read byte-by-byte. If you are reading a text file then you should be using a
BufferedReaderinstead. This converts a byte array intoString.Also, with any IO, you should always do it in a try/finally block to make sure you close it: