fix: save as new file when file already exists (#332)

Refs: #131
This commit is contained in:
Jan
2025-12-12 14:24:52 +01:00
committed by GitHub
parent 749c398aa6
commit c0d7f64551
2 changed files with 29 additions and 1 deletions

View File

@@ -20,6 +20,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- Fixed files from hidden folders showing up in storage tab browser ([#217])
- Fixed an issue where existing files were overwritten when saving new files ([#131])
## [1.3.0] - 2025-09-30
### Added
@@ -110,6 +111,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
[#250]: https://github.com/FossifyOrg/File-Manager/issues/250
[#251]: https://github.com/FossifyOrg/File-Manager/issues/251
[#267]: https://github.com/FossifyOrg/File-Manager/issues/267
[#131]: https://github.com/FossifyOrg/File-Manager/issues/131
[Unreleased]: https://github.com/FossifyOrg/File-Manager/compare/1.4.0...HEAD
[1.4.0]: https://github.com/FossifyOrg/File-Manager/compare/1.3.1...1.4.0

View File

@@ -58,7 +58,7 @@ class SaveAsActivity : SimpleActivity() {
?: filename.getMimeType()
val inputStream = contentResolver.openInputStream(source)
val destinationPath = "$destination/$filename"
val destinationPath = getAvailablePath("$destination/$filename")
val outputStream = getFileOutputStreamSync(destinationPath, mimeType, null)!!
inputStream!!.copyTo(outputStream)
rescanPaths(arrayListOf(destinationPath))
@@ -86,4 +86,30 @@ class SaveAsActivity : SimpleActivity() {
return filename.replace("[/\\\\<>:\"|?*\u0000-\u001F]".toRegex(), "_")
.takeIf { it.isNotBlank() } ?: "unnamed_file"
}
private fun getAvailablePath(destinationPath: String): String {
if (!getDoesFilePathExist(destinationPath)) {
return destinationPath
}
val file = File(destinationPath)
return findAvailableName(file)
}
private fun findAvailableName(file: File): String {
val parent = file.parent ?: return file.absolutePath
val name = file.nameWithoutExtension
val ext = if (file.extension.isNotEmpty()) ".${file.extension}" else ""
var index = 1
var newPath: String
do {
newPath = "$parent/${name}_$index$ext"
index++
} while (getDoesFilePathExist(newPath))
return newPath
}
}