public class InputStreamUtils {
private static final String CHARSET_NAME = "UTF-8";
private static final int BUFFER_SIZE = 1024;ide
/**
* 將字符串轉換成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();
}
}編碼