1. 程式人生 > >網路流進行轉化(String轉化,直接寫入檔案)

網路流進行轉化(String轉化,直接寫入檔案)

將網路流轉化為String

InputStream inputStream = url.openStream();   // 從URL上取得位元組流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int ch = -1;
byte[] buffer = new byte[1024 * 4];
while ((ch = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, ch);
}
baos.flush();
String responseXml = baos.toString(HTTP.UTF_8);  // 依據需求可以選擇要要的字元編碼格式


if (isr != null) {   // 列印最後結果
Log.i(TAG, "得到的字串是:" + responseXml);
}


把網路流直接寫入檔案

[java] view plaincopyprint?
  1. // 得到讀取的內容(流)
  2. // 使用迴圈來讀取獲得的資料,並寫入檔案
  3. FileOutputStream outFileStream = m_context.openFileOutput(fileName,  
  4.         Context.MODE_PRIVATE);  
  5. InputStream inPutSteam = urlConn.getInputStream();  
  6. byte[] bufferinPut = 
    newbyte[4096];  
  7. int lengthinPut = -1;  
  8. while ((lengthinPut = inPutSteam.read(bufferinPut)) != -1) {  
  9.     outFileStream.write(bufferinPut,0,lengthinPut);  
  10. }  
  11. //關閉檔案流
  12. inPutSteam.close();  
  13. outFileStream.close()