I have a folder full of images and videos in my RAW directory. I want to turn this folder into a file object in Kotlin, then traverse all the folders and files within and convert them into media that's usable for my app.
The directory that contains my media (I want to convert this into a file object, this is the issue I am having):
val basePath = Paths.get("").toAbsolutePath().toString()
traverse(db, File("$basePath/app/src/main/res/raw/media1")) // This is a directory, and it's not being seen using this code.
My traverse() method iterates through the media1 directory and converts all found images/videos to usable media for my app.
fun traverse(db: SQLiteDatabase?, dir : File) {
if (dir.exists()) {
val files = dir.listFiles()
if (files != null) {
for (i in 0 until files.count()) {
val file = files[i]
if (file.isDirectory) {
traverse(db, file)
} else {
saveFile(db, file) // This fun creates a database row for the media and saves the media file onto the local phone for later reference
}
}
}
}
}
I tried accessing the directory through the C drive, through the Paths.get command, calling R.raw. No matter what, it seems to not see the "media1" directory...
CodePudding user response:
I want to turn this folder into a file object in Kotlin, then traverse all the folders and files within and convert them into media that's usable for my app.
Sorry, that is not an option. You will be far better served moving this set of directories into assets/
rather than raw/
, then use AssetManager
to traverse the tree. However, even then, you do not get files, but rather InputStreams
, because neither assets nor resources are files on the phone's filesystem.
No matter what, it seems to not see the "media1" directory
Partly, that is because they are not files on the phone. Partly, that is because resources do not support subdirectories.
CodePudding user response:
This ended up being my solution:
val fields : Array<Field> = R.raw::class.java.fields
for (count in 0 until fields.count()) {
val resourceID = fields[count].getInt(fields[count])
val value = TypedValue()
context!!.resources.getValue(resourceID, value, true)
val inputStream: InputStream = context.resources.openRawResource(resourceID)
val file : File = createTempFile(fields[count].name, '.' value.string.toString().split('.')[1])
inputStream.use {input ->
file.outputStream().use {output ->
input.copyTo(output)
}
}
saveFile(db, file)
}
The individual media files were moved from their sub-directories and into the raw resource folder of the project.
Android studio doesn't let you traverse sub-directories, and resources must be manually loaded into File objects using input and output streams. I find it ridiculous that we have to jump through so many hoops to accomplish something so basic.