下载的图像不完整但图像仍然显示使用 Android 剪切?

Downloaded Image not complete but the image still shows cut using Android?

我有一个 Android 应用程序可以下载一些图像,使用正常。大多数时候,当发生错误(网络,磁盘space,...等)时会抛出异常,我只知道并删除catch块中的下载文件。

但是,有时会出现下载不完整,图片显示但被截断的情况。 (即图像的一半是可见的,左侧部分显示为白色)

关于如何检测此错误以便我删除文件并请求用户重新下载的任何建议?

代码如下:

private static int downloadFile(byte[] buffer, String fromUrl, File saveTo) {
    URL url;
    boolean conn = true;
    try {
        url = new URL(fromUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("connection", "close");
        connection.connect();
        // expect HTTP 200 OK, so we don't mistakenly save error report
        // instead of the file
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
            return DOWNLOAD_SERVER_INVALID_RESPONSE;
        //int fileLength = connection.getContentLength();
        // download the file
        InputStream input = connection.getInputStream();
        conn = false;
        FileOutputStream output = new FileOutputStream(saveTo);
        int count;
        //long total = 0;
        while ((count = input.read(buffer)) != -1) {
            output.write(buffer, 0, count);
            //total += count;
        }
        input.close();
        output.close();
        return DOWNLOAD_OK;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return DOWNLOAD_MALFORMED_URL;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return DOWNLOAD_FILE_NOT_FOUND;
    } catch (SocketException ex) {
        ex.printStackTrace();
        return DOWNLOAD_SERVER_INVALID_RESPONSE;
    } catch (UnknownHostException ex) {
        ex.printStackTrace();
        return DOWNLOAD_SERVER_INVALID_RESPONSE;
    } catch (IOException e) {
        e.printStackTrace();
        return conn ? DOWNLOAD_SERVER_INVALID_RESPONSE : DOWNLOAD_IO_EXCEPTION;
    }
}

我想既然你解释的图像是下载了一半的图像,你可以做一些事情,比如检查图像实际下载了多少,然后根据它决定是删除还是保留。在您的代码中,行 int fileLength = connection.getContentLength(); 将帮助您执行此操作。只需检查 fileLength 和下载的图像文件长度是否相等或接近相等。如果是,则说明下载成功。我猜,只是猜测,代码应该是这样的:

int fileLength = connection.getContentLength();
if (fileLength != -1) {
    if (fileLength == file.length()) {
        System.out.println("file is complete");
    } else {
        System.out.println("file is incomplete");
    }
} else {
    System.out.println("unknown if file is complete");
}

稍微调整一下,你应该会得到你想要的。

正如 greenapps 所指出的,您也可以使用这种方法:

  1. 分配一个 int 变量 int totalcount = 0;
  2. totalcount += count;
  3. 循环中递增
  4. 循环完成后,比较totalcountfileLength