我正在尝试在服务器上上传约 10 MB 的大文件,并意识到在 2.3.4 上,流在写入服务器之前首先写入内存,我通过查看堆内存转储来确认此行为,因为对于大文件它会导致 OutOfMemory 异常。我在 4.2 设备上看不到相同的行为。
以下是我正在使用的代码:
URL url = new URL(uri);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("PUT");
connection.setRequestProperty("content-type", "");
connection.setRequestProperty("Accept-Encoding", "");
connection.setFixedLengthStreamingMode((int)totalBytes);
out = new BufferedOutputStream(connection.getOutputStream());
fis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[32 * 1024];
int bytesRead = 0;
int totalBytesRead = 0;
while ((bytesRead = fis.read(buffer)) != -1)
{
totalBytesRead = totalBytesRead + bytesRead;
out.write(buffer, 0, bytesRead);// OOM Error
}
out.flush();