Question

I am trying to read a Stream which will read until it ends with some string. I came up with some solution but I do not believe it is very good solution because of lots of string conversion and call to method in loop. Could someone please suggest me better solution.

  private static String readUntilEndsWith(BufferedReader reader,
                                          String endString) throws IOException
  {
    StringBuffer buffer = new StringBuffer();
    while (!buffer.toString().endsWith(endString))
      buffer.append(reader.readLine());
    return buffer.toString();
  }
Was it helpful?

Solution

Read the current line only and evaluate it. If the line is ok, append it into your buffer and keep reading. This way you only evaluate the current line in the reader and not the whole content.

StringBuilder buffer = new StringBuilder();
String line = reader.readLine();
while (line != null && !line.endsWith(endString)) {
    buffer.append(line);
    line = reader.readLine();
}
if (line != null) {
    buffer.append(line);
}
return buffer.toString();

OTHER TIPS

If your endString is always a string that is in a line, then you can remake your condition to:

String line="";
do{
      line=reader.readLine();
      buffer.append(line);

}while (!line.endsWith(endString));

this way you do not have to convert your Buffer each time to a string.

P.S. i also recommend using StringBuilder instead of StringBuffer if your endString is however something that might be a sum of few lines, you can add something like:

if(endString.endsWith(line) {
    if(buffer.toString().endsWith(endString)
        return buffer.toString();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top