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