传入流得到字符串工具类

2种传入流得到字符串工具类

/***
 * 定义字符串操作的帮助类,帮助我们将InputStream -> String
 * (用的是BufferedReader)
 */
public class StringUtils {

    /****
     * 将得到的输入流 InputStream转换成为字符串的操作
     * @param is 需要转码的输入流
     * @param charset 需要转换的字符串编码方式 (主要有"utf-8"或者是"gbk")
     * @return 返回为转码好的字符串数据,如果返回为空,表示出现异常情况
     */
    public static String myEncode(InputStream is,String charset){
        //定义需要得到的字符串数据
        String result = null;

        try {
            //创建StringBuffer的对象,追加字符串
            StringBuffer sb = new StringBuffer();
            //转码InputStream ---> BufferedReader
            BufferedReader br = new BufferedReader(new InputStreamReader(is, charset));
            //定义临时变量
            String line = null;
            //循环
            while((line = br.readLine())!=null){
                //添加数据到StringBuffer当中
                sb.append(line).append("\n");
            }
            //关闭IO流
            br.close();
            is.close();
            //得到数据
            result = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回结果数据
        return result;
    }

}


public class StreamTools {
//  String jsonData = StreamTools.readStream(is);//这里有中文乱码问题
    /**
     * 根据 服务器输入流 得到 json数据 (用的是ByteArrayOutputStream)
     * @param is 服务器输入流
     * @return json数据
     */
    public static String readStream(InputStream is) {
        String data=null;

        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            byte[] buffer = new byte[8192];
            int len;
            while ((len= is.read())!=-1) {
                baos.write(buffer, 0, len);
            }
            is.close();
//          data = new String(baos.toString().getBytes("gbk"),"gbk");
            data = baos.toString("gbk");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值