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

时间:2015-08-20 17:59:50

标签: android bitmap filepath

我有以下方法从给定的URL下载图像。当我第一次运行适当的方法时,文件将保存到SD卡。当我重新运行这些方法,并检查给定路径末尾是否有文件时,图像不是(我用file.exists()检查),并返回null。这项活动的原因是什么? 代码在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 studio。谢谢您的帮助。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

如果您再次调用具有相同位置的功能,它将继续替换现有文件。尝试不同的位置。让我知道它是否成功。干杯!