inputStream 与 String 的互相转换
2015-06-21 09:26
323 查看
一. String 转换为InputStream
String str = "String 与 inputStream转换";
InputStream ins1 = new ByteArrayInputStream(str.getBytes());
InputStream ins2 = new ByteArrayInputStream(str.getBytes("UTF-8"));
二. InputStream 转为 String
方法一:利用bufferedReader
方法二:
方法三:
String str = "String 与 inputStream转换";
InputStream ins1 = new ByteArrayInputStream(str.getBytes());
InputStream ins2 = new ByteArrayInputStream(str.getBytes("UTF-8"));
二. InputStream 转为 String
方法一:利用bufferedReader
public String convertToString(InputStream is){
BufferedReader bReader = new BufferedReader(new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String line = null;
try {
while((line = bReader.readLine())!=null){
buffer.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
bReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return buffer.toString();
}
方法二:
public String convertToString(InputStream is){
StringBuffer buffer = new StringBuffer();
byte[] b = new byte[1024];
try {
for(int n; (n = is.read(b))!=-1;)
buffer.append(new String(b,0,n));
return buffer.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
方法三:
public String convertToString(InputStream is){
ByteArrayOutputStream os = new ByteArrayOutputStream();
int i = -1;
try {
while((i = is.read())!=-1){
os.write(i);
}
return os.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}finally{
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
相关文章推荐
- Java知多少(99)Graphics2D类的绘图方法
- 图 像处理相关研究
- solrj实现增量索引
- MySQL InnoDB存储引擎undo redo解析
- jdk环境配置
- [caffe]caffe资料收集
- 与成功有约
- 一般线性模型
- Commit message中Partial-Bug, Related-Bug等含义
- Android启动画面
- C++语言基础 例程 C++中的输入和输出
- JavaScript中圆括号()和方括号[]的一个特殊用法
- JavaScript中圆括号()和方括号[]的一个特殊用法
- 黑马程序员——JAVA笔记——线程
- 宏定义中的#,##
- Windows 10预览版升级正式版无需Win7/Win8.1授权
- C++语言基础 例程 C++的数据类型和运算符
- 8.17~8.18
- 谷歌上不去,长期的解决方案。在稳定高速Google和Gmail
- asp.net web 服务器端全局定时执行任务