static protected void htmlEncode(Writer writer, String string) throws IOException {
    int n = string.length();
    int writeNext = 0;
    for (int i = 0; i < n; ++i) {
      int ch = string.charAt(i);
      String encoded;
      if (ch >= 128)
        encoded = "&#" + ch + ";";
      else
        switch (ch) {
          case '<':
            encoded = "&lt;";
            break;
          case '>':
            encoded = "&gt;";
            break;
          case '&':
            encoded = "&amp;";
            break;
          case '\"':
            encoded = "&quot;";
            break;
          case '\'':
            encoded = "&#39;";
            break;
          default:
            encoded = null;
            break;
        }
      if (encoded != null) {
        writer.write(string, writeNext, i - writeNext);
        writer.write(encoded);
        writeNext = i + 1;
      }
    }
    if (writeNext < n) writer.write(string, writeNext, n - writeNext);
  }