Android(kotlin),如何获取资产文件路径?(在 pytorch 手机上)

bet*_*a22 5 android kotlin pytorch

我正在尝试 kotlin 的 PyTorch Mobile 教程。我想在资产文件中加载模块“model.pt”。但不知道在资产文件中加载模块。

Java(用 PyTorch 移动教程“hello world”编写)

Module module = Module.load(assetFilePath(this, "model.pt"));
Run Code Online (Sandbox Code Playgroud)

科特林

val module = Module.load("?????")
Run Code Online (Sandbox Code Playgroud)

Sau*_*rat 6

声明这个函数:

fun assetFilePath(context: Context, asset: String): String {
    val file = File(context.filesDir, asset)

    try {
        val inpStream: InputStream = context.assets.open(asset)
        try {
            val outStream = FileOutputStream(file, false)
            val buffer = ByteArray(4 * 1024)
            var read: Int

            while (true) {
                read = inpStream.read(buffer)
                if (read == -1) {
                    break
                }
                outStream.write(buffer, 0, read)
            }
            outStream.flush()
        } catch (ex: Exception) {
            e.printStackTrace()
        }
        return file.absolutePath
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return ""
}
Run Code Online (Sandbox Code Playgroud)

然后将其用作:

val module = Module.load(assetFilePath(this, "model.pt"))
Run Code Online (Sandbox Code Playgroud)