我下载的视频文件大于 Android 应用程序提供的内存空间。当它们在设备上时,MediaPlayer 可以很好地处理它们,因此它们的整体大小不是问题。 问题是,如果它们超过 byte[] 可以达到的相对较小的兆字节数,那么我在下载它们时会遇到可怕的 OutOfMemory 异常。
我打算的解决方案是直接将传入的字节流写入 SD 卡,但是,我使用的是 Apache Commons 库,我这样做的方式是尝试在视频提交之前读入整个视频回到我的身边。
我的代码是这样的:
HttpClient client = new HttpClient();
PostMethod filePost = new PostMethod(URL_PATH);
client.setConnectionTimeout(timeout);
byte [] ret ;
try{
if(nvpArray != null)
filePost.setRequestBody(nvpArray);
}catch(Exception e){
Log.d(TAG, "download failed: " + e.toString());
}
try{
responseCode = client.executeMethod(filePost);
Log.d(TAG,"statusCode>>>" + responseCode);
ret = filePost.getResponseBody();
....
我很好奇另一种方法是一次获取一个字节的字节流,然后将其写入磁盘。
最佳答案
您应该能够使用 PostMethod 对象的 GetResponseBodyAsStream 方法并将其流式传输到文件。这是一个未经测试的例子....
InputStream inputStream = filePost.getResponseBodyAsStream();
FileInputStream outputStream = new FileInputStream(destination);
// Per your question the buffer is set to 1 byte, but you should be able to use
// a larger buffer.
byte[] buffer = new byte[1];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1)
{
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
关于java - 能否绕过 HEAP 从 HTTP 直接将字节流写入 SDCard?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18808310/