2024-04-06

【Kotlin】Coroutine 複製 assets 的檔案到內部儲存空間

參考資料 ----

  1.  
  2. override fun onCreate(savedInstanceState: Bundle?) {
  3. super.onCreate(savedInstanceState)
  4. setContentView(R.layout.activity_main)
  5.  
  6. // 檢查內部儲存空間是否已存在檔案
  7. val file = File(this.filesDir, "mymusic.mp3")
  8. if(!file.exists()) {
  9. copyAssets()
  10. } else {
  11. Toast.makeText(this, "mymusic.mp3 已複製到私有儲存空間", Toast.LENGTH_LONG).show();
  12. }
  13. }
  14.  
  15. ...
  16. ...
  17.  
  18. // 複製 mymusic.mp3 至私有儲存空間
  19. private fun copyAssets() {
  20. val mScope = CoroutineScope(Job() + Dispatchers.IO)
  21. mScope.launch {
  22. try {
  23. val outfile = FileOutputStream(File(filesDir, "mymusic.mp3").path)
  24. val infile: InputStream = assets.open("mymusic.mp3")
  25. infile.copyTo(outfile)
  26. outfile.close()
  27. infile.close()
  28. } catch(err: IOException) {
  29. err.printStackTrace();
  30. }
  31. }
  32. }
  33.  


相關筆記 ----


沒有留言:

張貼留言