尽管标题与Stack Overflow中的其他标题非常相似,但我遇到的任何一种可能性似乎都不适合我。
我正在下载一个带有DownloadManager的文件(我之所以选择这种方式是因为我是android和kotlin的新手,我似乎快速通过DM下载文件,然后将其复制到内部存储中+从Download文件夹中删除它,而不是手动管理线程创建以直接处理下载到内部存储中。
然后我试图将其移动到内部存储中。文件可以是图像,但主要是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
}
我真的找不到入门级(forob!)的文档,所以我正在努力解决一个非常简单的问题,我猜...
好的,最后我设法解决了我的麻烦。我把这个答案的链接放在这里救了我的一天(最后我发现了):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()
}
不过,我认为,我只是将文件直接下载到内部存储中。