【问题标题】:How to move a file to Internal Storage (reserved app's memory) in Android with Kotlin?如何使用 Kotlin 将文件移动到 Android 中的内部存储(保留应用程序的内存)?
【发布时间】:2019-02-22 13:55:16
【问题描述】:

尽管标题与 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
}

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

【问题讨论】:

  • 好的,谢谢提示! :) 我不知道它只是自己反转了

标签: android kotlin stream android-internal-storage


【解决方案1】:

好的,我终于设法解决了我的问题。 我在这里放了答案的链接,它拯救了我的一天(终于找到了):save file to internal memory in 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()
}

不过,我想我会直接将文件下载到内部存储中。

【讨论】:

    猜你喜欢
    • 2019-06-27
    • 1970-01-01
    • 2023-03-10
    • 2021-10-11
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    相关资源
    最近更新 更多