Android 图像保存到SD卡覆盖现有文件
我正在成功地将一个图像保存在一个文件夹中的SD卡上 我遇到的问题是,如果我保存了多个文件,图像会覆盖以前保存的现有图像,因为文件名相同,所以它会覆盖现有图像 有没有什么方法可以让图像保存时,每次都用不同的名称保存,这样就不会覆盖 提前谢谢 以下是我目前掌握的情况:Android 图像保存到SD卡覆盖现有文件,android,bitmap,save,Android,Bitmap,Save,我正在成功地将一个图像保存在一个文件夹中的SD卡上 我遇到的问题是,如果我保存了多个文件,图像会覆盖以前保存的现有图像,因为文件名相同,所以它会覆盖现有图像 有没有什么方法可以让图像保存时,每次都用不同的名称保存,这样就不会覆盖 提前谢谢 以下是我目前掌握的情况: OutputStream output; Time now = new Time(); now.setToNow(); String time = now.toString();
OutputStream output;
Time now = new Time();
now.setToNow();
String time = now.toString();
// Retrieve the image from the res folder
BitmapDrawable drawable = (BitmapDrawable) mImageView.getDrawable();
Bitmap bitmap1 = drawable.getBitmap();
// Find the SD Card path
File filepath = Environment.getExternalStorageDirectory();
// Create a new folder in SD Card
File dir = new File(filepath.getAbsolutePath()
+ "/Wallpapers/");
dir.mkdirs();
// Create a name for the saved image
File file = new File(dir, "Wallpaper"+ time );
// Show a toast message on successful save
Toast.makeText(getActivity(), "Wallpaper saved with success!",
Toast.LENGTH_LONG).show();
try {
output = new FileOutputStream(file);
// Compress into png format image from 0% - 100%
bitmap1.compress(Bitmap.CompressFormat.PNG, 100, output);
output.flush();
output.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
使用:
并获取您试图保存文件的时间
然后,将其附加到文件名的末尾。
这样,您的文件将永远不会具有相同的名称,而是始终具有相同的前缀
要检查目录是否存在
File dir = new File(Environment.getExternalStorageDirectory() + "/mydirectory");
if(dir.exists() && dir.isDirectory()) {
// do something here
}
但是,没有SD卡的设备将无法按预期工作
Would there be any way I would be able to make it so when the image saves,
it saves with a different name each time so it doesn't overwrite?
是的,在使用file.exists()
保存之前,您需要检查目录中是否已存在同名文件。按如下方式操作:
File file = new File(dir, "Wallpaper.jpg");
if(file.exists()){
// assign different name to file
}
else{
// file not present with same name
}
无需检查文件是否存在,并为其指定新名称。看看我的答案我已经更新了我的代码,这样你就可以看到它现在是什么样子了,它仍然因为一些奇怪的原因不起作用。它只在我特别更改文件名时才起作用?我想这是因为你每次都在创建相同的目录。如果目录存在,则使用Cehck;如果目录不存在,则使用mkdir
File file = new File(dir, "Wallpaper.jpg");
if(file.exists()){
// assign different name to file
}
else{
// file not present with same name
}