您的位置:首页 > 理论基础 > 计算机网络

网络流进行转化(String转化,直接写入文件)

2013-03-06 13:18 281 查看
将网络流转化为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?

// 得到读取的内容(流)
// 使用循环来读取获得的数据,并写入文件
FileOutputStream outFileStream = m_context.openFileOutput(fileName,
Context.MODE_PRIVATE);
InputStream inPutSteam = urlConn.getInputStream();
byte[] bufferinPut = new byte[4096];
int lengthinPut = -1;

while ((lengthinPut = inPutSteam.read(bufferinPut)) != -1) {
outFileStream.write(bufferinPut,0,lengthinPut);
}
//关闭文件流
inPutSteam.close();
outFileStream.close();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: