String与InputStream相互转换

1.String to InputStream

  public static InputStream String2InputStream(String name) {
    return new ByteArrayInputStream(name.getBytes());
  }

2.InputStream to String

    这里提供几个方法。

 1   public static String InputStream2String(InputStream input,String encode) throws IOException {
 2     StringBuilder builder = new StringBuilder();
 3 
 4     InputStreamReader reader = new InputStreamReader(input,encode);
 5     BufferedReader bufferedReader = new BufferedReader(reader);
 6     String line = null;
 7     try {
 8       while ((line = bufferedReader.readLine()) != null) {
 9         builder.append(line);
10       }
11     } catch (IOException e) {
12       e.printStackTrace();
13     } finally {
14       input.close();
15     }
16     return builder.toString();
17   }
18 
19   public static String InputStream2String2(InputStream input) throws IOException {
20     StringBuffer buffer = new StringBuffer();
21     byte[] b = new byte[1024];
22     int n;
23     try {
24       while ((n = input.read(b)) != -1) {
25         buffer.append(new String(b, 0, n));
26       }
27     } catch (IOException e) {
28       e.printStackTrace();
29     } finally {
30       input.close();
31     }
32     return buffer.toString();
33   }
34 
35   public static String InputStream2String3(InputStream input) throws IOException {
36     ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
37     int i;
38     try {
39       while ((i = input.read()) != -1) {
40         outputStream.write(i);
41       }
42     } catch (IOException e) {
43       e.printStackTrace();
44     } finally {
45       input.close();
46     }
47     return outputStream.toString();
48   }