唯爱小粽子: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;
    }


你可能感兴趣的:(java,String,Inputstream,byte)