尽管标题为标题,与堆栈溢出中的其他类似,我遇到的任何可能性似乎都适合我。
我正在使用下载管理器下载文件(由于我是Android和Kotlin的新事实,我选择了这种方式,在我看来,Quicket可以通过DM下载文件,然后将其复制到内部存储中 从下载文件夹,而不是手动管理线程创建以直接处理内部存储中的下载)。
然后,我正在尝试将其移至内部存储中。这些文件可以是图像,但主要是mp3文件。现在,我正在开发MP3阅读器部分。下载还可以,但是我对将文件复制到Interal存储中遇到了问题这是我的代码:
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
}
我真的找不到入门级文档(noob!)文档,所以我在一个非常简单的事情上挣扎,我想...
好的,最后我设法解决了麻烦。我将这里放置在保存了一天的答案的链接(终于找到了它):将文件保存到Android中的内部内存?
中我简单地更改(只是从外部存储中使用副本)输入源,使其指向我自己的文件!我终于理解了" 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()
}
我认为,我只需直接将文件直接下载到内部存储中。