0

当我想从我的应用程序将图像保存到 Android 时,我遇到了这个奇怪的问题。图像已损坏,现在 Android 无法使用它们。我看不出我的代码有什么问题。

这是我的下载方法:

    public void createExternalStoragePublicPicture(String DownloadUrl, String fileName) {
    // Create a path where we will place our picture in the user's
    // public pictures directory.  Note that you should be careful about
    // what you place here, since the user often manages these files.  For
    // pictures and other media owned by the application, consider
    // Context.getExternalMediaDir().

    Log.i("Download", DownloadUrl);
    Log.i("File", fileName);

    File path = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File file = new File(path, fileName);

    try {
        // Make sure the Pictures directory exists.
        path.mkdirs();

        // Very simple code to copy a picture from the application's
        // resource into the external file.  Note that this code does
        // no error checking, and assumes the picture is small (does not
        // try to copy it in chunks).  Note that if external storage is
        // not currently mounted this will silently fail.
        URL url = new URL(DownloadUrl);
        URLConnection ucon = url.openConnection();

        InputStream is = ucon.getInputStream();
        OutputStream os = new FileOutputStream(file);
        byte[] data = new byte[is.available()];
        is.read(data);
        os.write(data);
        is.close();
        os.close();

        // Tell the media scanner about the new file so that it is
        // immediately available to the user.
        MediaScannerConnection.scanFile(this,
                new String[] { file.toString() }, null,
                new MediaScannerConnection.OnScanCompletedListener() {
            public void onScanCompleted(String path, Uri uri) {
                Log.i("ExternalStorage", "Scanned " + path + ":");
                Log.i("ExternalStorage", "-> uri=" + uri);
            }
        });
    } catch (IOException e) {
        // Unable to create file, likely because external storage is
        // not currently mounted.
        Log.w("ExternalStorage", "Error writing " + file, e);
    }
}

任何想法这里出了什么问题?

4

1 回答 1

0

可能is.available()不会像您期望的那样工作。通常你不应该依赖它,available()因为它没有严格指定它返回什么值。

请参阅InputStream:“认识到您不能使用此方法来调整容器大小并假设您可以读取整个流 [...]”,这一点尤为重要

使用常见的“循环”方法:

int c;
while ( (c = is.read(buf)) >= 0 ) {
  os.write(buf,0,c)
}

这可以确保您确实从源文件中读取了所有字节。

于 2012-05-23T09:20:59.153 回答