String与InputStream相互转换----------Java学习
来源:互联网 发布:淘宝卖水果和干货吗 编辑:程序博客网 时间:2024/05/21 11:48
String与InputStream相互转换
1.String to InputStream
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();
}
有这个需求是在网络爬虫中想把html代码保存为word形式的,也就是图片和文本结合的一种保存方式,
需要将 html转换为inputstream,,
- String与InputStream相互转换----------Java学习
- String与InputStream相互转换
- String与InputStream相互转换
- String与InputStream相互转换
- String与InputStream相互转换
- String与InputStream相互转换
- String与InputStream相互转换
- String与InputStream相互转换
- String与InputStream相互转换
- String与InputStream相互转换
- InputStream与String相互转换
- String与InputStream相互转换
- String与InputStream相互转换
- String与InputStream相互转换
- String与InputStream相互转换
- String与InputStream相互转换
- String与Inputstream相互转换
- String与InputStream相互转换
- JQuery 数组过滤 grep()例子
- IPC(SystemV) 之 共享内存
- Windows核心编程 第6章线程基础
- 编程算法之数组二分查找法
- HDU - 1421 搬寝室 - DP
- String与InputStream相互转换----------Java学习
- html知识笔记(一)——head和body标签
- C 开发学习 - 结构类型(枚举/结构/类型定义)
- 2 UVA 10394 Twin Primes
- ZOJ Problem Set - 3880||Demacia of the Ancients
- ora-28001:the password has expired.(密码失效)
- 开启编程之旅
- Android之MVC模式
- UNIX环境下使用tmux在虚拟终端复用窗口的方法