InputStream,String和Reader之间的转换

Posted 不止积累,重在掌握

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了InputStream,String和Reader之间的转换相关的知识,希望对你有一定的参考价值。

1、String –> InputStream
InputStrem is = new ByteArrayInputStream(str.getBytes());
or
ByteArrayInputStream stream
= new ByteArrayInputStream(str.getBytes());

 2、InputStream–>String


inputStream input;

StringBuffer out = new StringBuffer();
     byte[] b = new byte[4096];
     for (int n; (n = input.read(b)) != -1;) {
      out.append(new String(b, 0, n));
     }
out.toString();
3、Reader –>String
BufferedReader in = new BufferedReader(new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String line = " ";
while ((line = in.readLine()) != null){
buffer.append(line);
}
return buffer.toString();


4、String–>Reader
Reader reader = null;
BufferedReader r = new BufferedReader(reader);
StringBuilder b = new StringBuilder();
String line;
while((line=r.readLine())!=null) {
b.append(line);
b.append(“\\r\\n”);
}
b.toString();

from http://www.cnblogs.com/clarkchen/archive/2011/03/09/1978570.html

以上是关于InputStream,String和Reader之间的转换的主要内容,如果未能解决你的问题,请参考以下文章

相当于 InputStream 或 Reader 的 Files.readAllLines()?

Reader 和 InputStream 有啥区别?

Java中InputStream和Reader之间的转换(字符流和字节流怎么互相转换啊)

InputStream,InputStreamReader和Reader的关系

Java InputStream和Reader

Java中InputStream与Reader的区别