码迷,mamicode.com
首页 > 其他好文 > 详细

InputStream和OutputStream与String之间的转换

时间:2014-10-02 18:49:53      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   sp   div   c   

//1.字符串转inputstream
        String str="aaaaa";
        InputStream in = new ByteArrayInputStream(str.getBytes());
        
        //2.inputstream转字符串
        String result = readFromInputStream(inputStream);//调用处
        //将输入流InputStream变为String
            public String readFromInputStream(InputStream in) throws IOException {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = -1;
                while ((len = in.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                baos.close();
                in.close();
                
                byte[] lens = baos.toByteArray();
                String result = new String(lens,"UTF-8");//内容乱码处理
                
                return result;
            
            }
        //3.String写入OutputStream中
        OutputStream out = System.out;  
        out.write(str.getBytes()); 
        
        //4.outputStream转string
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        //向OutPutStream中写入,如 message.writeTo(baos); 
        baos.write(str.getBytes());
        String str1= baos.toString();  

 

InputStream和OutputStream与String之间的转换

标签:style   blog   color   io   os   ar   sp   div   c   

原文地址:http://www.cnblogs.com/liun1994/p/4004252.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!