android - 代码仅在第一次执行时保存文件 - Android

标签 android bitmap filepath

我有以下方法从给定的 URL 下载图像。当我第一次运行适当的方法时,文件被保存到 sdcard 中。当我重新运行这些方法并检查给定路径末尾是否有文件时,图像不存在(我检查 file.exists()),并返回 null。进行此 Activity 的任何原因? 代码在 input = url.openStream() 处特别失败。

public class DownloadAndReadImage {
    String strURL;
    int pos;
    Bitmap bitmap = null;

    // pass image url and Pos for example i:
    DownloadAndReadImage(String url,int position) {
        this.strURL = url;
        this.pos = position;
    }

    public String getBitmapLocation() {
        return "/sdcard/"+pos+".png";
    }

    public Bitmap getBitmapImage() {
        downloadBitmapImage();
        return readBitmapImage();
    }

    void downloadBitmapImage() {
        InputStream input;
        try {
            URL url = new URL (strURL);
            input = url.openStream();
            byte[] buffer = new byte[500*1024]; //or 500*1024
            OutputStream output = new FileOutputStream ("/sdcard/"+pos+".png");
            try {
                int bytesRead = 0;
                while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
                    output.write(buffer, 0, bytesRead);
                }
            }
            finally {
                output.close();
                input.close();
                buffer = null;
            }
        }
        catch(Exception e) {
            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
        }
    }

    Bitmap readBitmapImage() {
        BitmapFactory.Options bOptions = new BitmapFactory.Options();
        bOptions.inTempStorage = new byte[16*1024*1024];

        String imageInSD = "/sdcard/"+pos+".png";

        bitmap = BitmapFactory.decodeFile(imageInSD,bOptions);
        boolean exists = new File(imageInSD).exists();
        return bitmap;
    }
}

这是调用代码:

   private void saveImage() {
        DownloadAndReadImage dImage = new DownloadAndReadImage(imageAddress, count);
        image = dImage.getBitmapImage();
    }

这是我的异步代码

public void submitFile() {
    if(URLUtil.isValidUrl(imageAddress)) {
        new AsyncTask<Void, Void, Boolean>() {
            protected Boolean doInBackground(Void... voids) {
                boolean img = false;
                boolean youtube = false;
                HttpURLConnection connection = null;
                try {
                    URL url  = new URL(imageAddress);
                    connection = (HttpURLConnection)url.openConnection();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String contentType = connection.getHeaderField("Content-Type");
                img = contentType.startsWith("image/");
                if(img)
                    media = "image";
                if (!img) {
                    // Check host of url if youtube exists
                    Uri uri = Uri.parse(imageAddress);
                    if ("www.youtube.com".equals(uri.getHost())) {
                        media = "youtube";
                        youtube = true;
                    }
                }
                return img || youtube;
            }

            protected void onPostExecute(Boolean valid) {
                if (valid) {
                    Picasso.with(Demo.this).load(imageAddress).into(imagePreview);
                    saveImage();
                    //sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()))); //refreshes system to show saved file
                    submitted = true;
                    submit_but.setText("Encrypt");
                }
            }
        }.execute();
    }
}

我正在使用安卓工作室。谢谢您的帮助。

最佳答案

尝试确保您也关闭输入流。如果这没有帮助,请发布您用来调用下载位图的代码。

关于android - 代码仅在第一次执行时保存文件 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32125213/

相关文章:

java - 如何让File类使用相对路径?

java - 访问 fragment 中声明的微调器

android - 使简单的重复文本更新无限期地继续

c - 读取BMP文件并旋转

android - 如何将位图从一个坐标移动到另一个坐标 - Android 开发

file - 使用动态文件名保存 pandas excel 数据框

Bash/C shell : Are there any drawbacks about escaping all characters of a file path?

android - 我可以在编译过程中使用Byte Buddy转换已编译的类吗?

android - junit.framework.AssertionFailedError : Exception in constructor: (java. lang.NoClassDefFoundError)

c# - wp - 根据 slider 值将图像转换为灰度