質問

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();
  }
役に立ちましたか?

解決

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();

他のヒント

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();
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top