天天看點

JAVA資料流之間的轉換

http://blog.csdn.net/liuhenghui5201/article/details/8292552

JAVA資料流之間的轉換

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