转自:http://wesker0918.iteye.com/blog/286642和http://www.oschina.net/code/snippet_54371_3138两处
String --> InputStream
- InputStream StringToInputStream(String str){
- ByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes());
- return stream;
- }
InputStream --> String
- String inputStreamToString(InputStream is){
- BufferedReader in = new BufferedReader(new InputStreamReader(is));
- StringBuffer buffer = new StringBuffer();
- String line = "";
- while ((line = in.readLine()) != null){
- buffer.append(line);
- }
- return buffer.toString();
- }
int i = -1;
//org.apache.commons.io.output.ByteArrayOutputStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((i = is.read()) != -1) {
baos.write(i);
}
String content = baos.toString();
int i = -1;
byte[] b = new byte[1024];
StringBuffer sb = new StringBuffer();
while ((i = is.read(b)) != -1) {
sb.append(new String(b, 0, i));
}
String content = sb.toString();
字符串与输入流转换技巧
本文介绍了两种实用的方法来实现字符串与输入流之间的相互转换。一种是通过使用ByteArrayInputStream将字符串转换为InputStream;另一种则是利用BufferedReader从InputStream中读取数据并将其拼接成字符串。此外还展示了使用ByteArrayOutputStream进行转换的替代方案。
936

被折叠的 条评论
为什么被折叠?



