我使用以下代码将图像下载到我的 android 应用程序中:
private void download(URL url, File file) throws IOException {
Log.d(TAG, "download(): downloading file: " + url);
URLConnection urlConnection = url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
BufferedInputStream bufferStream;
OutputStream outputStream = null;
try {
bufferStream = new BufferedInputStream(inputStream, 512);
outputStream = new FileOutputStream(file);
byte[] buffer = new byte[512];
int current;
while ((current = bufferStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, current);
}
} finally {
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
}
}
此代码运行良好,但一些用户和测试人员抱怨照片不完整。我怀疑小型网络延迟会中断连接。所以我想检测是否下载了整个图像并且保存的文件是完整的图像。有什么方法可以从 BufferedInputStream 检测文件大小,还是有另一种方法可以检测下载完成?