geek的技术日志,记录每一次技术思考的闪光点。

java中string和inputStream转换及String与reader的互转

1、String –> InputStream

 

InputStrem is = new ByteArrayInputStream(str.getBytes());
或者
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();
复制代码
打赏作者

未经允许不得转载:极客技术 » java中string和inputStream转换及String与reader的互转

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址