輸入流和字串互轉InputStream2String和String2InputStream

吕金林發表於2024-04-11

輸入流轉字串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static String InputStream2String(InputStream in) {
InputStreamReader reader = null;
try {
reader = new InputStreamReader(in, "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
BufferedReader br = new BufferedReader(reader);
StringBuilder sb = new StringBuilder();
String line = "";
try {
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}

  

字串轉輸入流

1
2
3
4
5
6
7
8
9
public static InputStream String2InputStream(String str) {
ByteArrayInputStream stream = null;
try {
stream = new ByteArrayInputStream(str.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return stream;
}

  

相關文章