if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // SD card is mounted } else { // SD card not mounted }
确认SD卡上的文件系统是否是FAT32。如果是FAT32格式的文件系统,文件名不能包含特殊字符(例如“:”,“\”,“*”,“?”,“|”等)。如果文件名包含这些特殊字符,则文件无法被写入。
确认您是否有足够的空间在SD卡上创建新文件。可通过以下方法检查可用空间:
StatFs stats = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath()); long availableSpace = stats.getAvailableBlocksLong() * stats.getBlockSizeLong();
if(availableSpace > requiredSpace) { // Sufficient space is available on SD card } else { // Insufficient space available on SD card }
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { // Permission not granted, request permission ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION); } else { // Permission granted, create file on external storage }
在AndroidManifest.xml文件中,添加以下代码: