InputStream和String互相转换的方法

前言

下面是一些 InputStream转String,String转InputStream的方法,大家可以拿去即用


InputStream转String的方法

方法一:

public String inputStreamToString(InputStream inputStream)throws Exception{
        byte[] bytes = new byte[0];
        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }
        bytes = new byte[count];
        inputStream.read(bytes);
        String str = new String(bytes);
        return str;
    }

方法二:

public String inputStream2String(InputStream in) throws IOException {
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for   (int  n; (n = in.read(b)) != -1;)   {
            out.append(new String(b,  0,   n));
        }
        return out.toString();
    }

方法三:
 public String inputStream3String(InputStream inputStream) throws Exception{
        StringBuilder sb = new StringBuilder();
        String line;
        BufferedReader br=null;
        String str=null;

        try {
            br = new BufferedReader(new InputStreamReader(inputStream));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            str = sb.toString();
        }catch (Exception e){
            
        }finally {
            if (br!=null){
                br.close();
            }
        }
        return str;
    }

注:readLine()是读取流读数据的时候用的,同时会以字符串形式返回这一行的数据,调用一次就会读取一行数据,读取之后会跳到下一行,当读取完所有的数据时会返回null。


方法四:
public String inputStream4String(InputStream inputStream) throws Exception{
        String str=null;
        try ( ByteArrayOutputStream result = new ByteArrayOutputStream();
        ){
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                result.write(buffer, 0, length);
            }
            str = result.toString(StandardCharsets.UTF_8.name());
            result.close();
        }
        return str;
    }

String转InputStream

InputStrem is = new ByteArrayInputStream(str.getBytes());
或者
ByteArrayInputStream stream= new ByteArrayInputStream(str.getBytes());

我们还可以指定编码

InputStream   stream= new ByteArrayInputStream(str.getBytes("UTF-8"));  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值