-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathResolvedPath.kt
More file actions
57 lines (48 loc) · 1.54 KB
/
ResolvedPath.kt
File metadata and controls
57 lines (48 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.nitrofs
import android.content.ContentResolver
import android.content.Context
import android.net.Uri
import java.io.File
import androidx.core.net.toUri
import java.io.InputStream
import java.io.OutputStream
sealed class ResolvedPath {
data class Content(val uri: Uri) : ResolvedPath()
data class FilePath(val file: File) : ResolvedPath()
}
fun String.toResolvedPath(): ResolvedPath? {
return when {
startsWith("content://") || startsWith("file://") ->
this.toUri().toResolvedPath()
else -> ResolvedPath.FilePath(File(this))
}
}
fun Uri.toResolvedPath(): ResolvedPath? {
return when (scheme) {
ContentResolver.SCHEME_CONTENT ->
ResolvedPath.Content(this)
ContentResolver.SCHEME_FILE -> {
val p = path ?: return null
ResolvedPath.FilePath(File(p))
}
else -> null
}
}
fun ResolvedPath.openInputStream(context: Context): InputStream? {
return when (this) {
is ResolvedPath.Content -> context.contentResolver.openInputStream(uri)
is ResolvedPath.FilePath -> if (file.exists()) file.inputStream() else null
}
}
fun ResolvedPath.openOutputStream(context: Context, append: Boolean = false): OutputStream? {
return when (this) {
is ResolvedPath.Content -> {
val mode = if (append) "wa" else "w"
context.contentResolver.openOutputStream(uri, mode)
}
is ResolvedPath.FilePath -> {
file.parentFile?.mkdirs()
file.outputStream()
}
}
}