jw
04/27/2023, 11:36 PMLoe
04/28/2023, 12:17 AMandroid
module, but i’m still getting errors because of the file path
This is the function i’m calling from MainActivity
and none of the paths work:
fun readFile() {
// val path = "words.txt".toPath() // doesn't work
// val path = "src/main/words.txt".toPath() // doesn't work
val path = "android/src/main/words.txt".toPath() // doesn't work
val csvContent = FileSystem.SYSTEM.read(path) {
readUtf8()
}
Log.d("++csv:", csvContent)
}
Loe
04/28/2023, 12:18 AMwords.txt
is located:jw
04/28/2023, 12:24 AMjw
04/28/2023, 12:24 AMjessewilson
04/28/2023, 1:27 AMLoe
04/28/2023, 2:05 AMJeff Lockhart
04/29/2023, 12:09 AMgetAsset(asset: String): Source
interface, returning an Okio Source
stream.
For Android, assuming the common resources are in the apk bundle's assets, it's simply:
applicationContext.assets.open(asset).source()
In order to get common test files in src/commonTest/resources in the Android apk bundle assets, I symlinked that path to src/androidInstrumentedTest/resources/assets.
I've also implemented for JVM, iOS, macOS, Linux, and Windows as well. Native platforms require an additional gradle task to copy the files to the correct location in the bundle resources or runtime path.jessewilson
04/29/2023, 3:28 AMJeff Lockhart
04/30/2023, 1:02 AMoverride fun getAsset(asset: String): Source {
val target = when (Platform.osFamily) {
OsFamily.LINUX -> "linux"
OsFamily.WINDOWS -> "mingw"
else -> error("Unsupported platform: ${Platform.osFamily}")
} + Platform.cpuArchitecture.name.lowercase().replaceFirstChar(Char::titlecase)
val path = "build/bin/$target/debugTest/$asset".toPath()
return FileSystem.SYSTEM.source(path)
}
In order to get commonTest
resources in that directory alongside the test binary, I use this gradle copy task:
tasks.withType<KotlinNativeTest> {
val dir = name.substring(0, name.lastIndex - 3)
dependsOn(
tasks.register<Copy>("copy${name.capitalized()}Resources") {
from("src/commonTest/resources")
into("build/bin/$dir/debugTest")
}
)
}
Jeff Lockhart
04/30/2023, 1:13 AMcommonMain
and iosMain
resources to the iOS *.framework
directory with this gradle code, which handles frameworks, fat frameworks, and test binary scenarios for Darwin platforms.
Something like this works to get resources from the bundle:
override fun getAsset(asset: String): Source? {
val dotIndex = asset.lastIndexOf('.')
val name = asset.substring(0, dotIndex)
val type = asset.substring(dotIndex + 1)
val path = NSBundle.mainBundle
.pathForResource(name, type)
?: return null
return FileSystem.SYSTEM.source(path.toPath())
}
Jeff Lockhart
04/30/2023, 1:14 AMjvm*
and common*
source sets automatically. Accessing them is simply:
override fun getAsset(asset: String): Source? =
javaClass.getResource("/$asset")?.openStream()?.source()
Loe
06/28/2023, 6:19 PM