吾知网

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 6177|回复: 0
打印 上一主题 下一主题

java中byte,String,InputStream之间的转换

[复制链接]
跳转到指定楼层
楼主
发表于 2015-11-24 22:28:18 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
    • import java.io.ByteArrayInputStream;
    • import java.io.ByteArrayOutputStream;
    • import java.io.IOException;
    • import java.io.InputStream;
    • public class InputStreamUtils {
    •     final static int BUFFER_SIZE = 4096;
    •     // 将InputStream转换成String
    •     public static String InputStreamTOString(InputStream in) throws Exception {
    •         ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    •         byte[] data = new byte[BUFFER_SIZE];
    •         int count = -1;
    •         while ((count = in.read(data, 0, BUFFER_SIZE)) != -1)
    •             outStream.write(data, 0, count);
    •         data = null;
    •         return new String(outStream.toByteArray(), "ISO-8859-1");
    •     }
    •     // 将InputStream转换成某种字符编码的String
    •     public static String InputStreamTOString(InputStream in, String encoding)
    •             throws Exception {
    •         ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    •         byte[] data = new byte[BUFFER_SIZE];
    •         int count = -1;
    •         while ((count = in.read(data, 0, BUFFER_SIZE)) != -1)
    •             outStream.write(data, 0, count);
    •         data = null;
    •         return new String(outStream.toByteArray(), "ISO-8859-1");
    •     }
    •     // 将String转换成InputStream
    •     public static InputStream StringTOInputStream(String in) throws Exception {
    •         ByteArrayInputStream is = new ByteArrayInputStream(in.getBytes("ISO-8859-1"));
    •         return is;
    •     }
    •     // 将InputStream转换成byte数组
    •     public static byte[] InputStreamTOByte(InputStream in) throws IOException {
    •         ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    •         byte[] data = new byte[BUFFER_SIZE];
    •         int count = -1;
    •         while ((count = in.read(data, 0, BUFFER_SIZE)) != -1)
    •             outStream.write(data, 0, count);
    •         data = null;
    •         return outStream.toByteArray();
    •     }
    •     // 将byte数组转换成InputStream
    •     public static InputStream byteTOInputStream(byte[] in) throws Exception {
    •         ByteArrayInputStream is = new ByteArrayInputStream(in);
    •         return is;
    •     }
    •     // 将byte数组转换成String
    •     public static String byteTOString(byte[] in) throws Exception {
    •         InputStream is = byteTOInputStream(in);
    •         return InputStreamTOString(is);
    •     }
    • }



您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|吾知网 ( 粤ICP备13013563号-1 )

GMT+8, 2024-5-2 23:13 , Processed in 1.078125 second(s), 10 queries , Memcache On.

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表