Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read multiple lines from InputStreamReader (JAVA)

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?

like image 598
amitlicht Avatar asked Mar 14 '26 13:03

amitlicht


1 Answers

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.

like image 192
Jack Avatar answered Mar 16 '26 02:03

Jack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!