有一种方法可以返回某个目录的可用空间:
fun bytesAvailable(f: File): Long {
val stat = StatFs(f.path)
val bytesAvailable = stat.blockSize.toLong() * stat.availableBlocks.toLong()
return bytesAvailable
}
我有如何使用它:
val downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
bytesAvailable(backupFile)
我无法直接在手机上捕获此错误,但我看到了用户发布的此类崩溃报告:
Caused by java.lang.IllegalArgumentException: Invalid path: /storage/sdcard0/Download
android.os.StatFs.doStat (StatFs.java:46)
android.os.StatFs.<init> (StatFs.java:39)
com.nickapps.Diary.presentation.ui.fragments.settings.SettingsPresenter.bytesAvailable (SettingsPresenter.kt:187)
com.nickapps.Diary.presentation.ui.fragments.settings.SettingsPresenter$doSimpleExport$2.call (SettingsPresenter.kt:74)
com.nickapps.Diary.presentation.ui.fragments.settings.SettingsPresenter$doSimpleExport$2.call (SettingsPresenter.kt:26)
rx.internal.operators.CompletableFlatMapSingleToCompletable$SourceSubscriber.onSuccess (CompletableFlatMapSingleToCompletable.java:61)
rx.Single$18.onNext (Single.java:1896)
...
Caused by android.system.ErrnoException: statvfs failed: ENOENT (No such file or directory)
libcore.io.Posix.statvfs (Posix.java)
libcore.io.BlockGuardOs.statvfs (BlockGuardOs.java:298)
android.system.Os.statvfs (Os.java:459)
android.os.StatFs.doStat (StatFs.java:44)
android.os.StatFs.<init> (StatFs.java:39)
com.nickapps.Diary.presentation.ui.fragments.settings.SettingsPresenter.bytesAvailable (SettingsPresenter.kt:187)
com.nickapps.Diary.presentation.ui.fragments.settings.SettingsPresenter$doSimpleExport$2.call (SettingsPresenter.kt:74)
com.nickapps.Diary.presentation.ui.fragments.settings.SettingsPresenter$doSimpleExport$2.call (SettingsPresenter.kt:26)
此类例外仅在21个以上的设备上发生。授予运行时权限WRITE_EXTERNAL_STORAGE
。
这是一个错误吗?某些设备上可能不存在Download
文件夹吗?