Read a few lines from InputStreamReader (JAVA)

I have an InputStreamReader object. I want to read multiple lines in a buffer / array using a single function call (without breaking the array of string objects). Is there an easy way to do this?

+3
source share
2 answers

First of all, remember that it is InputStreamReadernot so effective, you should wrap it around the object BufferedReaderfor maximum performance.

With that in mind, 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();
}

Note that the readLine()return nullis EOF, so you should check and take care of it.

+3
source

, , . StringBuilder , BufferedReader, ,

0

Source: https://habr.com/ru/post/1736694/


All Articles