public class InputStreamUtils {
private static final String CHARSET_NAME = "UTF-8";
private static final int BUFFER_SIZE = 1024;
/**
* 将字符串转换成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();
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。