2011年8月30日 星期二

String, Stream互轉

  private static String streamToString(InputStream input) throws Exception {
    String output = "";
    while (input.available() > 0) {
      output += ((char) (input.read()));
    }
    return output;
  }
  private static OutputStream stringToStream(String charset) throws IOException {
    byte[] bytes = charset.getBytes();
    InputStream is = null;
    OutputStream os = null;
    is = new ByteArrayInputStream(charset.getBytes("UTF-8"));
    int numRead;
    while ((numRead = is.read(bytes)) >= 0) {
      os.write(bytes, 0, numRead);
    }
    return os;
  }