Save Multiple Files Without Replacing The One That Exists
I am trying to save multiple images in a particular folder first image is saving correctly but the next one just replaces the first one. How to save multiple images? How to give th
Solution 1:
You could use a counter variable in your Activity
:
int counter = 0;
Append it in your file name and increment it after a successful save:
File savedPic = new File(picturesDir.getAbsolutePath() + "/mynewpic" + counter + ".jpg");
try {
out = new FileOutputStream(savedPic);
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
counter++; // no exception thrown, increment the counter
} catch (Exception e) {
e.printStackTrace();
}
You should use some sort of persistent storage to store the current value of the counter, such as SharedPreferences
.
Or, instead of a counter you could just use some unique identifier, System.currentTimeMillis
for example, so you don't have to deal with keeping track of the values.
Solution 2:
set the timestamp as ImageName so everytime it will save with different Name..
for add timestamp refer :here
Solution 3:
Using recursive call, it can be achieved easily. Below is the code.
/**
* fileCount - to avoid overwrite and save file
* with order ie - test - (1).pdf, test - (2).pdf
*/
fun savePdf(directoryPath: String, fileName: String, fileCount: Int = 0) {
val newFileName = if (fileCount == 0) {
"$fileName.pdf"
} else {
"$fileName - ($fileCount).pdf"
}
val targetFilePath = File(directoryPath, newFileName)
if (targetFilePath.exists()) {
savePdf(directoryPath, fileName, fileCount + 1)
return
}
// add your logic to save file in targetFilePath
}
And call it like this in your code.
savePdf(directoryPath, fileName)
Post a Comment for "Save Multiple Files Without Replacing The One That Exists"