Storage Interactions¶
modernstorage-storage
is a library abstracting storage interactions on Android using the library
Okio. It relies on its FileSystem API, which provides a
set of methods to read and write files.
Instead of opening an InputStream
or OutputStream
and relies on different APIs to get file
metadata for MediaStore and Storage Access Framework DocumentProvider
, this library takes
Uri (changed to Path to make it work with Okio) as an input for all its
methods to read and write files but also get metadata.
Add dependency to project¶
modernstorage-storage
is available on mavenCentral()
.
// build.gradle
// modernstorage-storage requires Okio 3.x.x as a dependency
implementation("com.squareup.okio:okio:3.0.0")
implementation("com.google.modernstorage:modernstorage-storage:1.0.0-alpha06")
API reference¶
modernstorage-storage
API reference is available here.
Initialize before usage¶
To interact with the FileSystem API, you need to initialize an instance first:
import com.google.modernstorage.storage.AndroidFileSystem
val fileSystem = AndroidFileSystem(context)
Get Path from Uri¶
Call toOkioPath
to get a Path
from a Uri
:
val path = uri.toOkioPath()
Get Path from File¶
Call toOkioPath
to get a Path
from a File
:
val path = File(context.filesDir, "myfile.jpg").toOkioPath()
Copy a file¶
You can easily copy a file to another location by using the copy
method:
fileSystem.copy(originPath, targetPath)
Get file metadata¶
You can get the file size by using the method metadataOrNull
:
import com.google.modernstorage.storage.MetadataExtras.DisplayName
import com.google.modernstorage.storage.MetadataExtras.MimeType
val fileMetadata = fileSystem.metadataOrNull(uri.toOkioPath())
Log.d("ModernStorage/uri", uri.toString())
Log.d("ModernStorage/isRegularFile", metadata.isRegularFile.toString())
Log.d("ModernStorage/isDirectory", metadata.isDirectory.toString())
Log.d("ModernStorage/size", metadata.size.toString())
Log.d("ModernStorage/lastModifiedAtMillis", metadata.lastModifiedAtMillis.toString())
Log.d("ModernStorage/displayName", metadata.extra(DisplayName::class).value)
Log.d("ModernStorage/mimeType", metadata.extra(MimeType::class).value)
Read a Text file Uri from the Storage Access Framework¶
/**
* We register first an ActivityResult handler for Intent.ACTION_OPEN_DOCUMENT
* Read more about ActivityResult here: https://developer.android.com/training/basics/intents/result
*/
val actionOpenTextFile = registerForActivityResult(OpenDocument()) { uri ->
if(uri != null) {
// textPath is an instance of okio.Path
val textPath = uri.toOkioPath()
Log.d("ModernStorage/metadata", fileSystem.metadataOrNull(textPath).toString())
Log.d("ModernStorage/content", fileSystem.source(textPath).buffer().readUtf8())
}
}
// Open file picker
actionOpenTextFile.launch(arrayOf("text/*"))