保存的图像覆盖sd卡android

时间:2016-08-30 06:30:28

标签: android image download android-sdcard

在我的应用程序中,我允许用户从Url链接下载图像数量并将其存储在SD卡中。每次下载的新图像都会覆盖具有相同名称的上一个图像。所以最后我在SD卡中只有一张图片,最后一次下载。

     try {
            URL url = new URL(src);
            URLConnection connection = (URLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            bitmap = BitmapFactory.decodeStream(input);

            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

            String filename;
            Date date = new Date(0);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            filename = sdf.format(date);
            File file = new File(Environment.getExternalStorageDirectory() + File.separator + filename + ".jpg");

            try {
                file.createNewFile();
                FileOutputStream fo = new FileOutputStream(file);
                Toast.makeText(getApplicationContext(),filename,Toast.LENGTH_LONG).show();
                // 5
                fo.write(bytes.toByteArray());
                fo.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return bitmap;

        } catch (IOException e) {
            e.printStackTrace();

            return null;
        }

我需要帮助存储我下载的所有图像。

2 个答案:

答案 0 :(得分:2)

    try this:

         Random generator = new Random();
         int n = 10000;
         n = generator.nextInt(n);
         filename = sdf.format(date+ n);

答案 1 :(得分:1)

试试这个

 File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            getString(R.string.images));
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Image-" + n + ".jpg";
    File file = new File(mediaStorageDir, fname);