http://blog.csdn.net/liuhenghui5201/article/details/8292552
InputStream.read(byte[] b)
从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中。
OutputStream.write(byte[] b)
将 b.length 个字节从指定的 byte 数组写入此输出流。
PrintWriter(Writer out)
创建不带自动行刷新的新 PrintWriter。
String urlPath="";URL url=new URL(urlPath);
HttpURLConnectioncoon=
(HttpURLConnection)url.openConnection();
字符流->字节流:
String s=”asasaa”;
printWriter pw=new printWrite(conn.getoutputStream);
Pw.print(s); pw.flush();
byte[] s= str.getBytes();
字节流->字符流:
bufferedReader br=new bufferedRead(new inputStreamReader(conn.getinputStream);
String result=””;
While(String line=br.readLine()!=null){result+=line;}
InputStreamReader(new inputstream())
通常 Writer 将其输出立即发送到底层字符或字节流。除非要求提示输出,否则建议用 BufferedWriter 包装所有其 write() 操作可能开销很高的 Writer(如 FileWriters 和 OutputStreamWriters)。例如,
PrintWriter out
= new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
同理:BufferedReader in
= new BufferedReader(new FileReader("foo.in"));
1.字节流和字符流之间的转换
字节流转换成字符流可以用InputSteamReader/OutputStreamWriter相互转换.
输出字符流
- OutputStream out = System.out;//打印到控制台。
- OutputStream out = new FileOutputStream("D:\\demo.txt");//打印到文件。
- OutputStreamWriter osr = new OutputStreamWriter(out);//输出
- BufferedWriter bufw = new BufferedWriter(osr);//缓冲
- String str = "你好吗?\r\n我很好!";//你好吗?
- bufw.write(str);
- bufw.flush();
- bufw.close();
读取字节流
- InputStream in = System.in;//读取键盘的输入。
- InputStream in = new FileInputStream("D:\\demo.txt");//读取文件的数据。
//将字节流向字符流的转换。要启用从字节到字符的有效转换,可以提前从底层流读取更多的字节.
- InputStreamReader isr = new InputStreamReader(in);//读取
- char []cha = new char[1024];
- int len = isr.read(cha);
- System.out.println(new String(cha,0,len));
- isr.close();
2.怎么把字符串转为流. 下面的程序可以理解把字符串line 转为流输出到aaa.txt中去
FileOutputStream fos = null;
fos = new FileOutputStream("C:\\aaa.txt");
String line="This is 1 line";
fos.write(line.getBytes());
fos.close();
- static String src = "今天的天气真的不好";
- public static void main(String[] args) throws IOException {
- StringBuilder sb = new StringBuilder();
- byte[] buff = new byte[1024];
- //从字符串获取字节写入流
- InputStream is = new ByteArrayInputStream(src.getBytes("utf-8"));
- int len = -1;
- while(-1 != (len = is.read(buff))) {
- //将字节数组转换为字符串
- String res = new String(buff, 0, len);
- Sb.append(res);}