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);}