在sdcard android中保存图像覆盖

Num*_*air 0 android image overwrite save sd-card

我正在使用以下代码保存图像

        FrameLayout mainLayout = (FrameLayout) findViewById(R.id.frame);
            //  File root = Environment.getExternalStorageDirectory();
            //  File file = new File(root, "androidlife.jpg");
//              File file = new File(Environment.getExternalStorageDirectory()
//                        + File.separator + "/test.jpg");
                Random fCount = new Random();
                // for (int i = 0; i < 10; i++) { Comment by Lucifer
                  int roll = fCount.nextInt(600) + 1;
                  //System.out.println(roll);


                File file = new File(Environment.getExternalStorageDirectory()
                        + File.separator + "/test" + String.valueOf(roll) +".jpg" );

                Bitmap b = Bitmap.createBitmap(mainLayout.getWidth(),
                        mainLayout.getHeight(), Bitmap.Config.ARGB_8888);
                Canvas c = new Canvas(b);
                mainLayout.draw(c);
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(file);

                    if (fos != null) {
                        b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
                        fos.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            //  }  Comment by Lucifer
Run Code Online (Sandbox Code Playgroud)

它可以完美地保存图像,但是当我按两次保存按钮时会覆盖...可能是什么问题?任何消化?

Sha*_*wal 6

File file = new File(Environment.getExternalStorageDirectory()
                        + File.separator + "/test.jpg");
if(!file.exists()){
    try {
      file.createNewFile();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}else{
    file.delete();
    try {
        file.createNewFile();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Bitmap b = Bitmap.createBitmap(mainLayout.getWidth(),
mainLayout.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
mainLayout.draw(c);
FileOutputStream fos = null;
try {
    fos = new FileOutputStream(file);
    if (fos != null) {
        b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
        fos.close();
    }
} catch (Exception e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)