如何在 Kotlin 多平台项目中的commanMain 模块中使用 okio 读取文件?

Sve*_*ven 13 kotlin okio kotlin-multiplatform

我正在尝试读取/写入commonMain模块中的文件。

我使用 Android Studio 向导为 Android 和 iOS 创建了一个新的 Kotlin 多平台应用程序。( New -> New Project ... -> Koltin Multiplatform App)

然后我将 okio 添加为shared/build.gradle.kts文件中 common 的依赖项。

    sourceSets {
        val okio = "3.3.0"
        val commonMain by getting {
            dependencies {
                implementation("com.squareup.okio:okio:$okio")
            }
        }
        ...
Run Code Online (Sandbox Code Playgroud)

在模块 commonMain 中,我无法访问FileSystem.SYSTEM( Unresolved Reference: SYSTEM),因此无法读取或写入任何文件。

在模块中iOSMainandroidMain可以访问FileSystem.SYSTEM. 这是预期的行为吗?这需要我为所有 okio api 编写一个expected/actual映射。或者还有其他方法吗?

或者我是否需要以不同的方式配置我的项目才能访问-ModuleFileSystem.SYSTEM内部commonMain

shared/build.gradle

plugins {
    kotlin("multiplatform")
    kotlin("native.cocoapods")
    id("com.android.library")
}

kotlin {
    android()
    iosX64()
    iosArm64()
    iosSimulatorArm64()

    cocoapods {
        summary = "Some description for the Shared Module"
        homepage = "Link to the Shared Module homepage"
        version = "1.0"
        ios.deploymentTarget = "14.1"
        podfile = project.file("../iosApp/Podfile")
        framework {
            baseName = "shared"
        }
    }
    
    sourceSets {
        val okio = "3.3.0"
        val commonMain by getting {
            dependencies {
                implementation("com.squareup.okio:okio:$okio")
            }
        }
        val commonTest by getting {
            dependencies {
                implementation(kotlin("test"))
            }
        }
        val androidMain by getting
        val androidTest by getting
        val iosX64Main by getting
        val iosArm64Main by getting
        val iosSimulatorArm64Main by getting
        val iosMain by creating {
            dependsOn(commonMain)
            iosX64Main.dependsOn(this)
            iosArm64Main.dependsOn(this)
            iosSimulatorArm64Main.dependsOn(this)
        }
        val iosX64Test by getting
        val iosArm64Test by getting
        val iosSimulatorArm64Test by getting
        val iosTest by creating {
            dependsOn(commonTest)
            iosX64Test.dependsOn(this)
            iosArm64Test.dependsOn(this)
            iosSimulatorArm64Test.dependsOn(this)
        }
    }
}

android {
    namespace = "de.pixel.kmmpodstryout"
    compileSdk = 32
    defaultConfig {
        minSdk = 21
        targetSdk = 32
    }
}
Run Code Online (Sandbox Code Playgroud)

来自向导生成的示例应用程序中 commonMain 中的 Greetings.kt:

package de.pixel.kmmpodstryout

import okio.FileSystem
import okio.Path.Companion.toPath

class Greeting {
    private val platform: Platform = getPlatform()

    fun greet(): String {
        val path = "helloworld.txt".toPath()

        FileSystem.SYSTEM <--- "Unresolved Reference SYSTEM"

        return "Hello, ${platform.name} ${readFile()}!"
    }
}
Run Code Online (Sandbox Code Playgroud)