返回顶部

收藏

java读取InputStream文本内容的几种方式

更多

第一种方式:只使用java的标准库,使用java.util.Scanner

public static String convertStreamToString(java.io.InputStream is) {
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

第二种方式:使用java.io.Reader和StringBuilder

public static String slurp(final InputStream is, final int bufferSize)
{
  final char[] buffer = new char[bufferSize];
  final StringBuilder out = new StringBuilder();
  try {
    final Reader in = new InputStreamReader(is, "UTF-8");
    try {
      for (;;) {
        int rsz = in.read(buffer, 0, buffer.length);
        if (rsz < 0)
          break;
        out.append(buffer, 0, rsz);
      }
    }
    finally {
      in.close();
    }
  }
  catch (UnsupportedEncodingException ex) {
    /* ... */
  }
  catch (IOException ex) {
      /* ... */
  }
  return out.toString();
}

第三种方式: 借助于apache commons的IOUtils类将InputStream复制到StingReader中:

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();

标签:java,IO,字符串

收藏

0人收藏

支持

0

反对

0

发表评论