首页 > 解决方案 > 如何使用 Kotlin 将文件移动到 Android 中的内部存储(保留应用程序的内存)?

问题描述

尽管标题与 Stack Overflow 中的其他标题非常相似,但我遇到的任何一种可能性似乎都不适合我。

我正在使用 DownloadManager 下载文件(我之所以选择这种方式是因为我是 android 和 kotlin 的新手,在我看来,通过 DM 下载文件然后将其复制到内部存储中 + 从下载文件夹中删除它,而不是手动管理线程创建以将下载直接处理到内部存储中)。

然后我试图把它移到内部存储中。这些文件可以是图像,但主要是 mp3 文件。现在我正在开发 mp3 阅读器部分。下载没问题,但是我在将文件复制到内部存储时遇到问题这是我的代码:

if(myDownloadKind == "I"){ // string "I" stands for "internal"

    println("myTag - into BroadCast for inner")

    var myStoredFile:String = uri.toString()
    println("mytag - myStoredFile: $myStoredFile")
    // here I try to convert the mp3 file into a ByteArray to copy it
    var data:ByteArray = Files.readAllBytes(Paths.get(myStoredFile))
    println("myTag - data: $data")

    var myOutputStream: FileOutputStream
    // write file in internal storage
    try {
        myOutputStream = context.openFileOutput(myStoredFile, Context.MODE_PRIVATE)
        myOutputStream.write(data) // NOT WORKING!!
    }catch (e: Exception){
        e.printStackTrace() 
    }


} else if (myDownloadKind == "E"){
  // now this doesn't matter, Saving in external storage is ok
}

我真的找不到入门级(对于新手!)文档,所以我正在努力解决一件非常简单的事情,我猜......

标签: androidkotlinstreamandroid-internal-storage

解决方案


好的,最后我设法解决了我的问题。我在这里放了答案的链接,它拯救了我的一天(终于我找到了):将文件保存到 android 的内部存储器?

我只是更改了(只是为了维护来自外部存储的副本)InputStream 源,使其指向我自己的文件!此外,我终于理解了“InputStream 系统”,当然,我以 Kotlin 式的方式重写了 while 循环

try {
    println("myTag - into BroadCast for inner")

    val downloadedFile = File(uri.toString())
    val fileInputStream = FileInputStream(downloadedFile)
    println("myTag - input stream of file: $fileInputStream")

    val inputStream = fileInputStream
    val inStream = BufferedInputStream(inputStream, 1024 * 5)

    val file = File(context.getDir("Music", Context.MODE_PRIVATE), "/$myFilename$myExtensionVar")
    println("myTag - my cavolo di file: $file")

    if (file.exists()) {
        file.delete()
    }
    file.createNewFile()

    val outStream = FileOutputStream(file)
    val buff = ByteArray(5 * 1024)

    var len = 0
    while(inStream.read(buff).also { len = it } >= 0){
        outStream.write(buff, 0, len)
    }

    outStream.flush()
    outStream.close()
    inStream.close()

} catch (e: Exception) {
    e.printStackTrace()
}

但是,我认为,我将直接将文件直接下载到内部存储中。


推荐阅读