Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added stream-based file handling from uri #131

Merged
merged 3 commits into from
Jan 22, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 31 additions & 10 deletions app/src/main/java/com/daniebeler/pfpixelix/utils/GetFile.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,44 @@ package com.daniebeler.pfpixelix.utils

import android.content.Context
import android.net.Uri
import android.provider.MediaStore
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream

object GetFile {
fun getFile(uri: Uri, context: Context): File? {
// Retrieves a file from URI, copies it and returns the copied file
val fileName = getFileName(uri)
if (!fileName.isNullOrEmpty()) {
val copyFile = File(context.getExternalFilesDir("Pixelix"), fileName)
copy(context, uri, copyFile)
return File(copyFile.absolutePath)
}
return null
}

val contentResolver = context.contentResolver

val cursor = contentResolver.query(uri, null, null, null, null)
cursor?.use {
if (it.moveToFirst()) {
val columnIndex = it.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
val filePath = it.getString(columnIndex)
private fun getFileName(uri: Uri): String? {
// Extract file name from given Uri
val path = uri.path ?: return null
val lastSlashIndex = path.lastIndexOf("/")
return if (lastSlashIndex != -1) path.substring(lastSlashIndex + 1) else null
}

return File(filePath)
private fun copy(context: Context, uri: Uri, file: File) {
// copy the contents of a file from the uri to the destination file
try {
val inputStream: InputStream? = context.contentResolver.openInputStream(uri)
inputStream?.use { input ->
val outputStream: OutputStream = FileOutputStream(file)
outputStream.use { output ->
input.buffered().copyTo(output.buffered())
}
}
}
return null
catch (e: IOException) {
e.printStackTrace()
}
}
}