温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

InputStream与String/byte[]相互转换

发布时间:2020-08-03 21:13:15 来源:网络 阅读:728 作者:DennisRuan 栏目:移动开发

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();
 }
 
}

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI