我的 android 应用程序使用一个 API 来发送一个多部分的 HTTP 请求。我成功地得到了这样的回应:
post.setEntity(multipartEntity.build());
HttpResponse response = client.execute(post);
响应是电子书文件(通常是 epub 或 mobi)的内容。我想将其写入具有指定路径的文件,让我们说“/sdcard/test.epub”。
文件可能高达 20MB,因此它需要使用某种流,但我无法理解它。谢谢!
最佳答案
这是一个简单的任务,您需要 WRITE_EXTERNAL_STORAGE
使用权限.. 然后只需检索 InputStream
InputStream is = response.getEntity().getContent();
创建文件输出流
FileOutputStream fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "test.epub"))
;
从 is 读取并用 fos 写入
int read = 0;
byte[] buffer = new byte[32768];
while( (read = is.read(buffer)) > 0) {
fos.write(buffer, 0, read);
}
fos.close();
is.close();
编辑,检查tyoo
关于java - 如何将 HttpResponse 下载到文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19733612/