JAVA中String和byte[]和InputStream之间的相互转换

在项目开发过程中,我们经常需要对String、byte数组、InputStream进行一些必要的转换,今天,我们分别的来实现一下这些不同类型的数据的转换

1、byte[]转String

/**
     * byte[]转String
     * @param bytes
     * @return
     * @throws Exception
     */
    public static String bytesToString(byte[] bytes) throws Exception{
        String result = new String(bytes,"UTF-8");
        return result;
    }

2、String转byte[]

/**
     * String转byte[]
     * @param str
     * @return
     */
    public static byte[] StringToBytes(String str){
        byte[] bytes = str.getBytes();
        return bytes;
    }

3、InputStream转String

/**
     * InputStream转String
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static String InputStreamToString(InputStream inputStream) throws Exception{
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int bufferSize = 1024;
        byte[] data = new byte[bufferSize];
        int count = -1;
        while((count = inputStream.read(data,0,bufferSize)) != -1){
            outputStream.write(data,0,count);
            data = null;
        }
        return new String(outputStream.toByteArray(),"UTF-8");
    }

4、String转InputStream

/**
     * String转InputStream
     * @param str
     * @return
     * @throws Exception
     */
    public static InputStream StringToInputStream(String str) throws Exception{
        ByteArrayInputStream inputStream = new ByteArrayInputStream(str.getBytes("UTF-8"));
        return inputStream;
    }

5、InputStream转byte[]

/**
     * InputStream转Byte[]
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static byte[] InputStreamToBytes(InputStream inputStream) throws Exception{
        int bufferSize = 1024;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] data = new byte[bufferSize];
        int count = -1;
        while((count = inputStream.read(data,0,bufferSize))!= -1){
            outputStream.write(data,0,count);
            data = null;
        }

        return outputStream.toByteArray();
    }

6、byte[]转InputStream

/**
     * byte[]转InputStream
     * @param bytes
     * @return
     * @throws Exception
     */
    public static InputStream BytesToInputStream(byte[] bytes) throws Exception{
        ByteArrayInputStream is = new ByteArrayInputStream(bytes);
        return is;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

有梦想的攻城狮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值