zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    hdu5587 BestCoder Round #64 (div.2)
    hdu5569 BestCoder Round #63 (div.2)
    hihocoder1257(构造)(2015北京ACM/ICPC)
    hihocoder 1249(2015ACM/ICPC北京)
    hihocoder1258(水)(2015ACM/ICPC北京站)
    hihiocoder 1255(搜索)(2015ACM/ICPC北京站)
    习题9-8 uva1631
    习题9-8 Uva1632
    Orz
    习题9-6 uva 10723
  • 原文地址:https://www.cnblogs.com/vijozsoft/p/5048878.html
Copyright © 2011-2022 走看看