URLConnection urlConn = url.openConnection(); // 打开网站链接s
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8")); // 实例化输入流,并获取网页代码
String s; // 依次循环,至到读的值为空
StringBuilder sb = new StringBuilder();
while ((s = reader.readLine()) != null) {
sb.append(s);
}
reader.close();
String str = sb.toString();
====================下面的方法有点恶心,改了改,看起来好多了===========================
原文:http://blog.csdn.net/soundtravel/article/details/6927006
String str = "";//add your string content
InputStream inputStream = new ByteArrayInputStream(str.getBytes());
1 package org.kodejava.example.io;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.InputStream;
5
6 publicclass StringToStream {
7 publicstaticvoid main(String[] args) {
8 String text ="Converting String to InputStream Example";
9
10 /*
11 * Convert String to InputString using ByteArrayInputStream class.
12 * This class constructor takes the string byte array which can be
13 * done by calling the getBytes() method.
14 */
15 try {
16 InputStream is =new ByteArrayInputStream(text.getBytes("UTF-8"));
17 } catch (UnsupportedEncodingException e) {
18 e.printStackTrace();
19 }
20 }
21 }
22
1、字符串转inputStream
String string;
//......
InputStream is = new ByteArrayInputStream(string.getBytes());
2、InputStream转字符串
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i;
while ((i = is.read()) != -1) {
baos.write(i);
}
String str = baos.toString();
System.out.println(str);
3、String写入OutputStream
OutputStream os = System.out;
os.write(string.getBytes());
4、OutputStream写入String
这听起来有点荒谬,OutputStream本来就是输出源,还写入String?
不过最近项目里确实遇到了个类似的问题,比如 SOAPMessage.writeTo(OutputStream os) 这个方法,是将SOAPMessage的内容写到一个输出流中,而我想得到这个流的内容,总不能把他先写进文件再去读这个文件吧,研究了好半天,终于想起可以如下这般:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//向OutPutStream中写入,如 message.writeTo(baos);
String str = baos.toString();
将InputStream/OutputStream转换成string
这里需要用到一个特殊的类ByteArrayOutputStream,利用他,我们可以将输出流在内存中直接转换成String类型。
具体代码如下:
首先从输入流中将数据读出来写入ByteArrayOutputStream,然后再将其转换成String.
InputStream in = urlconn.getInputStream();//获取输入流
ByteArrayOutputStream bos = new ByteArrayOutputStream();
//读取缓存
byte[] buffer = new byte[2048];
int length = 0;
while((length = in.read(buffer)) != -1) {
bos.write(buffer, 0, length);//写入输出流
}
in.close();//读取完毕,关闭输入流
// 根据输出流创建字符串对象
new String(bos.toByteArray(), "UTF-8");
//or
//bos.toString("UTF-8");
根据同样的原理,我们可以将outputstream直接转换成String对象。
指定一下字符集
byte[] b = str.getBytes("utf-8");
String s = new String(b,"utf-8");
OUTPUTSTREAM中方法WRITE用法