public class InputStreamUtils {
private static final String CHARSET_NAME = "UTF-8";
private static final int BUFFER_SIZE = 1024;
创新互联专注于中大型企业的网站设计、网站建设和网站改版、网站营销服务,追求商业策划与数据分析、创意艺术与技术开发的融合,累计客户成百上千,服务满意度达97%。帮助广大客户顺利对接上互联网浪潮,准确优选出符合自己需要的互联网运用,我们将一直专注成都品牌网站建设和互联网程序开发,在前进的路上,与客户一起成长!
/**
* 将字符串转换成InputStream
* @param string
* @return
* @throws UnsupportedEncodingException
*/
public static InputStream string2InputStream(String string) throws UnsupportedEncodingException {
ByteArrayInputStream inputStream = new ByteArrayInputStream(string.getBytes(CHARSET_NAME));
return inputStream;
}
/**
* 将InputStream转换成指定编码的String
* @param is
* @return
* @throws Exception
*/
public static String inputStream2String(InputStream is) throws Exception {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] data = new byte[BUFFER_SIZE];
int len = -1;
while (-1 != (len = is.read(data, 0, BUFFER_SIZE))) {
os.write(data, 0, len);
}
return new String(os.toByteArray(), CHARSET_NAME);
}
/**
* 将byte[]转换成IntputStream
* @param buf
* @return
*/
public static InputStream byte2InputStream(byte[] buf) {
ByteArrayInputStream inputStream = new ByteArrayInputStream(buf);
return inputStream;
}
/**
* 将IntputStream转换成byte[]
* @param is
* @return
* @throws IOException
*/
public static byte[] inputStream2Byte(InputStream is) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] date = new byte[BUFFER_SIZE];
int len = -1;
while (-1 != (len = is.read(date, 0, BUFFER_SIZE))) {
os.write(date, 0, BUFFER_SIZE);
}
return os.toByteArray();
}
}