Skip to content

Commit c0d7f64

Browse files
authored
fix: save as new file when file already exists (#332)
Refs: #131
1 parent 749c398 commit c0d7f64

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
2020

2121
### Fixed
2222
- Fixed files from hidden folders showing up in storage tab browser ([#217])
23+
- Fixed an issue where existing files were overwritten when saving new files ([#131])
2324

2425
## [1.3.0] - 2025-09-30
2526
### Added
@@ -110,6 +111,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
110111
[#250]: https://github.com/FossifyOrg/File-Manager/issues/250
111112
[#251]: https://github.com/FossifyOrg/File-Manager/issues/251
112113
[#267]: https://github.com/FossifyOrg/File-Manager/issues/267
114+
[#131]: https://github.com/FossifyOrg/File-Manager/issues/131
113115

114116
[Unreleased]: https://github.com/FossifyOrg/File-Manager/compare/1.4.0...HEAD
115117
[1.4.0]: https://github.com/FossifyOrg/File-Manager/compare/1.3.1...1.4.0

app/src/main/kotlin/org/fossify/filemanager/activities/SaveAsActivity.kt

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ class SaveAsActivity : SimpleActivity() {
5858
?: filename.getMimeType()
5959
val inputStream = contentResolver.openInputStream(source)
6060

61-
val destinationPath = "$destination/$filename"
61+
val destinationPath = getAvailablePath("$destination/$filename")
6262
val outputStream = getFileOutputStreamSync(destinationPath, mimeType, null)!!
6363
inputStream!!.copyTo(outputStream)
6464
rescanPaths(arrayListOf(destinationPath))
@@ -86,4 +86,30 @@ class SaveAsActivity : SimpleActivity() {
8686
return filename.replace("[/\\\\<>:\"|?*\u0000-\u001F]".toRegex(), "_")
8787
.takeIf { it.isNotBlank() } ?: "unnamed_file"
8888
}
89+
90+
private fun getAvailablePath(destinationPath: String): String {
91+
if (!getDoesFilePathExist(destinationPath)) {
92+
return destinationPath
93+
}
94+
95+
val file = File(destinationPath)
96+
return findAvailableName(file)
97+
}
98+
99+
private fun findAvailableName(file: File): String {
100+
val parent = file.parent ?: return file.absolutePath
101+
val name = file.nameWithoutExtension
102+
val ext = if (file.extension.isNotEmpty()) ".${file.extension}" else ""
103+
104+
var index = 1
105+
var newPath: String
106+
107+
do {
108+
newPath = "$parent/${name}_$index$ext"
109+
index++
110+
} while (getDoesFilePathExist(newPath))
111+
112+
return newPath
113+
}
114+
89115
}

0 commit comments

Comments
 (0)