Here you can find the source of saveStreamAsString(InputStream is)
Parameter | Description |
---|---|
is | InputStream to be read |
public static String saveStreamAsString(InputStream is) throws IOException
//package com.java2s; /**/* w w w . j a va 2s. c o m*/ * Copyright 2010 Newcastle University * * http://research.ncl.ac.uk/smart/ * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; public class Main { private static final String ENCODING = "UTF-8"; private static final String DEFAULT_CONTENT_CHARSET = ENCODING; /** * Read data from Input Stream and save it as a String. * * @param is InputStream to be read * @return String that was read from the stream */ public static String saveStreamAsString(InputStream is) throws IOException { return toString(is, ENCODING); } /** * Get the entity content as a String, using the provided default character set * if none is found in the entity. * If defaultCharset is null, the default "UTF-8" is used. * * @param is input stream to be saved as string * @param defaultCharset character set to be applied if none found in the entity * @return the entity content as a String * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE * @throws IOException if an error occurs reading the input stream */ public static String toString(final InputStream is, final String defaultCharset) throws IOException { if (is == null) { throw new IllegalArgumentException( "InputStream may not be null"); } String charset = defaultCharset; if (charset == null) { charset = DEFAULT_CONTENT_CHARSET; } Reader reader = new InputStreamReader(is, charset); StringBuilder sb = new StringBuilder(); int l; try { char[] tmp = new char[4096]; while ((l = reader.read(tmp)) != -1) { sb.append(tmp, 0, l); } } finally { reader.close(); } return sb.toString(); } private static final String toString(Object from) { return (from == null) ? null : from.toString(); } }