JAVA數據流之間的轉換

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相互轉換.

輸出字符流

  1.  OutputStream out = System.out;//打印到控制檯。  
  2.  OutputStream out = new FileOutputStream("D:\\demo.txt");//打印到文件。  
  3.             OutputStreamWriter osr = new OutputStreamWriter(out);//輸出  
  4. BufferedWriter bufw = new BufferedWriter(osr);//緩衝 
  1. String str = "你好嗎?\r\n我很好!";//你好嗎?  
  2.             bufw.write(str);  
  3.             bufw.flush();  
  4.             bufw.close(); 

讀取字節流

  1. InputStream in = System.in;//讀取鍵盤的輸入。  
  2. InputStream in = new FileInputStream("D:\\demo.txt");//讀取文件的數據。  

//將字節流向字符流的轉換。要啓用從字節到字符的有效轉換,可以提前從底層流讀取更多的字節.  

  1.         InputStreamReader isr = new InputStreamReader(in);//讀取  
  1.  char []cha = new char[1024];  
  2.         int len = isr.read(cha);  
  3.         System.out.println(new String(cha,0,len));  
  4.         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();

字符串與字節流轉換

  1. static String src = "今天的天氣真的不好";  
  2.     public static void main(String[] args) throws IOException {  
  3.           StringBuilder sb = new StringBuilder();
  4.         byte[] buff = new byte[1024];  
  5.         //從字符串獲取字節寫入流  
  6.         InputStream is = new ByteArrayInputStream(src.getBytes("utf-8"));  
  7.         int len = -1;  
  8.         while(-1 != (len = is.read(buff))) {  
  9.             //將字節數組轉換爲字符串  
  10.             String res = new String(buff, 0, len);  
  11.             Sb.append(res);}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章