首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用getExternalStoragePublicDirectory会损坏安卓文件

使用getExternalStoragePublicDirectory会损坏安卓文件
EN

Stack Overflow用户
提问于 2012-05-23 16:53:21
回答 1查看 965关注 0票数 0

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

以下是我的下载方法:

代码语言:javascript
复制
    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);
    }
}

你知道这里出了什么问题吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-05-23 17:20:59

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

参见InputStream:“特别重要的是要认识到,您不能使用此方法来调整容器的大小,并假定您可以读取整个流...")

使用常见的“循环”-approach:

代码语言:javascript
复制
int c;
while ( (c = is.read(buf)) >= 0 ) {
  os.write(buf,0,c)
}

这样可以确保您真正读取了源文件中的所有字节。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10716597

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档