views:

614

answers:

2

I have an InputStreamReader object. I want to read multiple lines into a buffer/array using one function call (without crating a mass of string objects). Is there a simple way to do so?

A: 

First of all mind that InputStreamReader is not so efficient, you should wrap it around a BufferedReader object for maximum performance.

Taken into account this you can do something like this:

public String readLines(InputStreamReader in)
{
  BufferedReader br = new BufferedReader(in);
  // you should estimate buffer size
  StringBuffer sb = new StringBuffer(5000);

  try
  {
    int linesPerRead = 100;
    for (int i = 0; i < linesPerRead; ++i)
    {
      sb.append(br.readLine());
      // placing newlines back because readLine() removes them
      sb.append('\n');
    }
  }
  catch (Exception e)
  {
    e.printStackTrace();
  }

  return sb.toString();
}

Mind that readLine() returns null is EOF is reached, so you should check and take care of it.

Jack
The objective in NOT to read line by lines, since it fills my heap with redundant string objects and makes the GC go wild. I wanted to read from an inputstreamreader (using a bufferedReader /whatever), without creating many String objects. Perhaps read directly into a buffer (without creating a string in the middle), or otherwise read multiple lines to avoid the string garbage...
amitlicht
what about using a __RandomAccessFile__ to read directly a buffer of bytes? Also the whole file (__readFull(byte[] b)__)
Jack
Strings are *very* optimized in JVM v. 1.6. Have you been using a profiler and really spotted an issue? Or are you just guessing?
incarnate
A: 

If you have some delimiter for multiple lines you can read that many characters using read method with length and offset. Otherwise using a StringBuilder for appending each line read by BufferedReader should work well for you without eating up too much temp memory

Fazal