String与InputStream相互转换

1.String to InputStream

1 String str = "String与InputStream相互转换";
2 InputStream   in_nocode   =   new   ByteArrayInputStream(str.getBytes());   
3 InputStream   in_withcode   =   new   ByteArrayInputStream(str.getBytes("UTF-8"));   

2.InputStream to String 

    这里提供几个方法。

方法1:  

 1 public String convertStreamToString(InputStream is) {   
 2 
 3    BufferedReader reader = new BufferedReader(new InputStreamReader(is));   
 4 
 5         StringBuilder sb = new StringBuilder();   
 6 
 7     
 8 
 9         String line = null;   
10 
11         try {   
12 
13             while ((line = reader.readLine()) != null) {   
14 
15                 sb.append(line + "/n");   
16 
17             }   
18 
19         } catch (IOException e) {   
20 
21             e.printStackTrace();   
22 
23         } finally {   
24 
25             try {   
26 
27                 is.close();   
28 
29             } catch (IOException e) {   
30 
31                 e.printStackTrace();   
32 
33             }   
34 
35         }   
36 
37     
38 
39         return sb.toString();   
40 
41     }   

方法2:

1 public   String   inputStream2String   (InputStream   in)   throws   IOException   { 
2         StringBuffer   out   =   new   StringBuffer(); 
3         byte[]   b   =   new   byte[4096]; 
4         for   (int   n;   (n   =   in.read(b))   !=   -1;)   { 
5                 out.append(new   String(b,   0,   n)); 
6         } 
7         return   out.toString(); 
8 } 

方法3:

1 public   static   String   inputStream2String(InputStream   is)   throws   IOException{ 
2         ByteArrayOutputStream   baos   =   new   ByteArrayOutputStream(); 
3         int   i=-1; 
4         while((i=is.read())!=-1){ 
5         baos.write(i); 
6         } 
7        return   baos.toString(); 
8 }
原文地址:https://www.cnblogs.com/vijozsoft/p/5048878.html