String与InputStream相互转换

本是古典 何须时尚 2022-09-20 15:15 283阅读 0赞

1.String to InputStream

String str = “String与InputStream相互转换”;

InputStream in = new ByteArrayInputStream(str.getBytes());

InputStream in = new ByteArrayInputStream(str.getBytes(“UTF-8”));

建议使用这种方式,指定编码后不易乱码。

2.InputStream to String

  1. 这里提供几个方法。

方法1:

public String convertStreamToString(InputStream is) {

BufferedReader reader = new BufferedReader(new InputStreamReader(is));

  1. StringBuilder sb = new StringBuilder();
  2. String line = null;
  3. try \{
  4. while ((line = reader.readLine()) != null) \{
  5. sb.append(line + "/n");
  6. \}
  7. \} catch (IOException e) \{
  8. e.printStackTrace();
  9. \} finally \{
  10. try \{
  11. is.close();
  12. \} catch (IOException e) \{
  13. e.printStackTrace();
  14. \}
  15. \}
  16. return sb.toString();
  17. \}

方法2:

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

方法3:
public static String inputStream2String(InputStream is) throws IOException{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i=-1;
while((i=is.read())!=-1){
baos.write(i);
}
return baos.toString();
}

发表评论

表情:
评论列表 (有 0 条评论,283人围观)

还没有评论,来说两句吧...

相关阅读