String与InputStream相互转换

来源:互联网 发布:天府立交数据 编辑:程序博客网 时间:2024/05/22 04:47

String与InputStream相互转换

标签: stringbytenull
128704人阅读 评论(4)收藏举报
本文章已收录于:
分类:
作者同类文章X

    1.String to InputStream

    String str = "String与InputStream相互转换";

    InputStream   in_nocode   =   new   ByteArrayInputStream(str.getBytes());  
    InputStream   in_withcode   =   new   ByteArrayInputStream(str.getBytes("UTF-8"));  

     

     

    2.InputStream to String

        这里提供几个方法。

    方法1:

      public String convertStreamToString(InputStream is) {   

       BufferedReader reader = new BufferedReader(new InputStreamReader(is));   

            StringBuilder sb = new StringBuilder();   

        

            String line = null;   

            try {   

                while ((line = reader.readLine()) != null) {   

                    sb.append(line + "/n");   

                }   

            } catch (IOException e) {   

                e.printStackTrace();   

            } finally {   

                try {   

                    is.close();   

                } catch (IOException e) {   

                    e.printStackTrace();   

                }   

            }   

        

            return sb.toString();   

        }   

     

    方法2:

    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();

    方法3:
    public   static   String   inputStream2String(InputStream   is)   throws   IOException{
            ByteArrayOutputStream   baos   =   new   ByteArrayOutputStream();
            int   i=-1;
            while((i=is.read())!=-1){
            baos.write(i);
            }
           return   baos.toString();
    }


     

    3
    0
     
     

    我的同类文章

    http://blog.csdn.net
    • JSON--Java与AJAX(Jquery)2010-02-08
    • ExcelUtils--excel报表模板引擎2009-11-19
    • HttpURLConnection超时处理2009-09-02
    • java验证日期格式2009-07-24
    • java.util.Date 与java.sql.Date相互转换2009-07-21
    • 关于select option自定义标签的说明2009-12-15
    • 正则——验证时间2009-09-03
    • 汉字转换拼音2009-07-24
    • Java中执行Shell(.sh)和windows批量处理(.bat)2009-07-21
    • 巧用系统属性2009-07-15
    更多文章
    0 0