Skip to content

Commit 6ecbc9c

Browse files
authored
🔀 Merge pull request #470 from HTossy/fix/truncate-data-overwriting
[Android] Fix: Truncate a file's data explicitly when overwriting a file on Android.
2 parents c50a21a + b83983d commit 6ecbc9c

File tree

1 file changed

+17
-3
lines changed

1 file changed

+17
-3
lines changed

filekit-core/src/androidMain/kotlin/io/github/vinceglb/filekit/PlatformFile.android.kt

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import android.annotation.SuppressLint
44
import android.content.Intent
55
import android.net.Uri
66
import android.os.Build
7+
import android.os.ParcelFileDescriptor
78
import android.provider.DocumentsContract
89
import android.provider.OpenableColumns
910
import android.webkit.MimeTypeMap
@@ -348,10 +349,23 @@ public actual fun PlatformFile.sink(append: Boolean): RawSink = when (androidFil
348349
// Use "wt" (write+truncate) for overwrite, "wa" (write+append) for append
349350
// This ensures existing file content is properly truncated when overwriting
350351
val mode = if (append) "wa" else "wt"
351-
FileKit.context.contentResolver
352-
.openOutputStream(androidFile.uri, mode)
353-
?.asSink()
352+
val fos = FileKit.context.contentResolver
353+
.openFileDescriptor(androidFile.uri, mode)
354+
?.let{ ParcelFileDescriptor.AutoCloseOutputStream(it) }
354355
?: throw FileKitException("Could not open output stream for Uri")
356+
357+
// If overwriting, explicitly set the size to 0
358+
// This is necessary because Truncate does not work well for Google Drive Uri.
359+
if (!append) {
360+
try {
361+
fos.channel.truncate(0)
362+
} catch (e: Exception) {
363+
fos.close()
364+
throw e
365+
}
366+
}
367+
368+
fos.asSink()
355369
}
356370
}
357371

0 commit comments

Comments
 (0)