Improve performance while reading from a BufferedReader.

N

Nishi Bhonsle

Hi:

I have the following code to read from a BufferedReader and save it to a string (contents separated by \n).
Is there anyway that I can improve the performance of this? Currently this operation runs over longer duration for not so big a file.

Thanks.
==========================================================

java.io.InputStream is = new BufferedInputStream(new FileInputStream("abc.xml"));
BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8"));

String fileContents;
String newContents = " ";
String lineSeparator = System.getProperty("line.separator");

while ((fileContents = in.readLine()) != null)
{
newContents=newContents.concat(fileContents);
newContents=newContents.concat(lineSeparator);

}
 
T

Thomas Weidenfeller

Nishi said:
I have the following code to read from a BufferedReader and save it to a string (contents separated by \n).

This is not what your code does. Your code does

(a) Remove the file's line separators

(b) Add the platform-specific line separator. You are not adding a '\n'.
You are adding whatever specific separator your platform uses.

(c) Create a lot of String objects

Is this really what you want?

If you need to read the file line-by-line and get rid of any line
separator, then use readLine(). But use a StringBuffer or StringBuilder
to re-concatenate the lines.

If you don't need the line separators removed, get rid of the buffered
reader, and instead read the data in to a char array.

In principle I advice against reading complete files into memory. Such
applications don't scale well. It is extremely easy for someone to crash
such an application or the whole OS by providing a huge file (on Unix
/dev/random or /dev/zero come handy for this task).

Instead, read a line or some buffer, process the line or buffer, and
read the next line or buffer.

/Thomas
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top