String与InputStream相互转换
2013-10-29 15:25
337 查看
1.String to InputStream
String str = "String与InputStream相互转换";
2.InputStream to String
这里提供几个方法。
方法1:
方法2:
方法3:
String str = "String与InputStream相互转换";
InputStream in_nocode = new ByteArrayInputStream(str.getBytes()); InputStream in_withcode = new ByteArrayInputStream(str.getBytes("UTF-8"));
2.InputStream to String
这里提供几个方法。
方法1:
public String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "/n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); }
方法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(); }
相关文章推荐
- 如何向外行解释机器学习
- 五、说说git reset命令
- CAS服务器配置
- 使用Microsoft.DirectX和Microsoft.DirectX.Sound进行录音时遇到的异常
- php四种基础算法:冒泡,选择,插入和快速排序法
- SNMP常用OID查询
- mysql服务器查询慢原因分析与解决方法小结
- 使用键盘Keyboard操控Winform(2)-传送按键SendKey对照表
- 父亲与茶
- 我的电脑文件打开的很慢怎么回事?
- MySQL定时器开启、调用实现代码
- Linux命令mount用例
- 〖Linux〗zigbee实验之cc2430的cc debugger固件升级实录
- MySql中常用语句
- 在JSP里使用CKEditor和CKFinder
- C语言浮点数除法求三角形面积
- COM组件简介
- javascript 学习笔记之模块化编程
- P1297 小气的小B
- Effective STL 笔记 -- Item 9: Choose carefully among erasing options