Java 中base64和输入流相互转换的方法

轩辕暗神 1年前 ⋅ 338 阅读
 /**
 * input流 转 base64 
 * @param 输入流
 * @return base64字符串
 */
 private static String inputStream2Base64( InputStream is) throws Exception {
        byte[] data = null;
        try {
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = is.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    throw new Exception("输入流关闭异常");
                }
            }
        }
        return Base64.getEncoder().encodeToString(data);
    }

/**
 * base64 转 input流
 * @param base64字符串
 * @return 输入流
 */
private static InputStream base2InputStream(String base64string) {
    ByteArrayInputStream stream = null;
    try {
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] bytes1 = decoder.decodeBuffer(base64string);
        stream = new ByteArrayInputStream(bytes1);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return stream;
}

全部评论: 0

    我有话说: