Improve performance while reading from a BufferedReader.

Discussion in 'Java' started by Nishi Bhonsle, Jul 20, 2004.

  1. 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);

    }
    Nishi Bhonsle, Jul 20, 2004
    #1
    1. Advertising

  2. Nishi Bhonsle wrote:
    > 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
    Thomas Weidenfeller, Jul 20, 2004
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. hb
    Replies:
    2
    Views:
    490
  2. Marc Twain
    Replies:
    5
    Views:
    4,775
    Andrew Thompson
    Jan 15, 2004
  3. Bob
    Replies:
    5
    Views:
    16,551
    tuldom84
    Jul 15, 2012
  4. R
    Replies:
    8
    Views:
    3,809
    Tom Forsmo
    Oct 21, 2006
  5. Replies:
    12
    Views:
    13,878
    Roedy Green
    Jun 29, 2007
Loading...

Share This Page