1、清单配置
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
如果
targetSdkVersion >=29 而又没有限定SD卡目录,则需在 application 配置
android:requestLegacyExternalStorage="true"
2、动态权限申请(targetSdkVersion >=23时需要)
3、创建文件夹
/**
* 创建文件夹---之所以要一层层创建,是因为一次性创建多层文件夹可能会失败!
*/
public static boolean createFileDir(File dirFile) {
if (dirFile == null) return true;
if (dirFile.exists()) {
return true;
}
File parentFile = dirFile.getParentFile();
if (parentFile != null && !parentFile.exists()) {
//父文件夹不存在,则先创建父文件夹,再创建自身文件夹
return createFileDir(parentFile) && createFileDir(dirFile);
} else {
boolean mkdirs = dirFile.mkdirs();
boolean isSuccess = mkdirs || dirFile.exists();
if (!isSuccess) {
Log.e("FileUtil", "createFileDir fail " + dirFile);
}
return isSuccess;
}
}
4、创建文件
public static File createFile(String dirPath, String fileName) {
try {
File dirFile = new File(dirPath);
if (!dirFile.exists()) {
if (!createFileDir(dirFile)) {
Log.e(TAG + "createFile dirFile.mkdirs fail");
return null;
}
} else if (!dirFile.isDirectory()) {
boolean delete = dirFile.delete();
if (delete) {
return createFile(dirPath, fileName);
} else {
Log.e(TAG + "createFile dirFile !isDirectory and delete fail");
return null;
}
}
File file = new File(dirPath, fileName);
if (!file.exists()) {
if (!file.createNewFile()) {
Log.e(TAG + "createFile createNewFile fail");
return null;
}
}
return file;
} catch (Exception e) {
Log.e(TAG + "createFile fail :" + e.getMessage());
e.printStackTrace();
return null;
}
}