code: private static String trimBuffer(StringBuilder textBuf, int end, boolean trim) {
          if (!trim) {
              return textBuf.substring(0, end);
          }
  
          int start = 0;
          boolean leadingLF = false;
          boolean tailingLF = false;
          char c;
  
          // leading whitespace
          for (int i = 0; i < end; i++) {
              c = textBuf.charAt(i);
  
              if (c == LF || c == CR) {
                  leadingLF = true;
              } else if (!Character.isWhitespace(c)) {
                  start = i;
                  break;
              }
          }
  
          if (leadingLF && start == 0) {
              return String.valueOf(LF);
          }
  
          // trailing whitespace
          for (int i = end - 1; i > start; i--) {
              c = textBuf.charAt(i);
  
              if (c == LF || c == CR) {
                  tailingLF = true;
              } else if (!Character.isWhitespace(c)) {
                  end = i + 1;
                  break;
              }
          }
  
          // restore a new line character which is leading whitespace
          if (leadingLF) {
              textBuf.setCharAt(--start, LF);
          }
  
          // restore a new line character which is tailing whitespace
          if (tailingLF) {
              textBuf.setCharAt(end++, LF);
          }
  
          return textBuf.substring(start, end);
      }
docs: Returns a copy of the string, with leading and trailing whitespaces stripped.
  <pre>
  "   \r\n   aaa  \r\n  bbb  "   ==&gt;   "\naaa  \n  bbb"
  "  aaa    \r\n   bbb   \r\n  "   ==&gt;   "aaa\nbbb\n"
  </pre>
  
  @param textBuf the string builder object
  @param end the ending index, exclusive.
  @param trim whether to trim
  @return the trimmed string