i'm saving image in my directory with same name (for a purpose) but when file is already exists there it won't get overwritten , how do i know that ? because when i'm saving this file the already existing file is not changing but when i use a different name for my file it works. so what i want is to replace the existing file with a new one. so far this is what i'm trying :
content.setDrawingCacheEnabled(true);
Bitmap bitmap = content.getDrawingCache(); // an bitmap file for saving
File file = new File(context.getApplicationContext().getFilesDir() + "/img.jpg"); //here's the path where i'm saving my file
if (file.exists()){
file.delete(); // here i'm checking if file exists and if yes then i'm deleting it but its not working
}
String path = file.getPath();
try {
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 60, ostream);
savedFile = new File(path);
ostream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
i'm doing another check right after deleting existing file :
if (file.exists()){
Toast.makeText(context , "Still EXISTS",Toast.LENGTH_SHORT).show();
}
and this time file is not here cause the toast is not appearing.
First, Let insert the permission in your AndroidManifest.xml file (less than Android 6.0 version)
android:name="android.permission.WRITE_INTERNAL_STORAGE" />
Then, use the below code to write the bitmap to file
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
File file = new File(path, "FitnessGirl"+".jpg"); // the File to save to
fOut = new FileOutputStream(file);
Bitmap pictureBitmap = content.getDrawingCache();// Your bitmap
//Bitmap pictureBitmap = getImageBitmap(myurl); // obtaining the Bitmap
pictureBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut); // saving the Bitmap to a file compressed as a JPEG with 85% compression rate
fOut.flush();
fOut.close(); // do not forget to close the stream
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
Add this line to Your Code
FileWriter fw = new FileWriter(myDir + "/score.jpg", false);
Try this,
boolean result = Files.deleteIfExists(file.toPath());
Also make sure you have write permission enabled!
PS: From Android Lollipop you need the runtime permission and the permission already set in manifest file won't work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With