/**
* 获得系统sdcard路径
*/
public static String getDirectoryPath() {
return Environment.getExternalStorageDirectory().getPath();
}
/**
* 检测sdcard是否可用
*/
public static boolean available() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
/**
* 初始化文件夹没有新建否则不动
*/
public final synchronized boolean mkdir(String... filePaths) {
try {
for (String filePath : filePaths) {
if (BuildConfig.DEBUG)
Logger.log(TAG, TAG + "->mkdir()->filePath:" + filePath);
if (filePath == null) {
return false;
}
if (!filePath.endsWith(File.separator))//如果以文件分隔符结尾则证明是文件夹
filePath = filePath.substring(0, filePath.lastIndexOf(File.separatorChar));
File file = new File(filePath);
if (!file.exists()) {//不存在
file.mkdirs();//创建文件夹
} else if (file.isFile()) {//如果是文件则重建
file.delete();
file.mkdirs();
}//如果已有文件夹则不动
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 在文件夹内放置文件以防系统识别内部多媒体文件
*/
private void hintMediaFile(String... filePaths) {
for (String filePath : filePaths) {
try {
if (filePath == null) {
break;
}
if (!filePath.endsWith(File.separator)) {
filePath = filePath + File.separatorChar;
}
File file = new File(filePath + ".nomedia");
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 删除文件
*/
private void deleteFile(File file) {
if (file.isFile()) {
deleteFileSafely(file);
return;
}
if (file.isDirectory()) {
File[] childFile = file.listFiles();
if (childFile == null || childFile.length == 0) {
deleteFileSafely(file);
return;
}
for (File f : childFile) {
deleteFile(f);
}
deleteFileSafely(file);
}
}
/**
* 安全删除文件(解决:open failed: EBUSY (Device or resource busy))
* @param file
* @return
*/
private boolean deleteFileSafely(File file) {
if (file != null) {
String tmpPath = file.getParent() + File.separator + System.currentTimeMillis();
File tmp = new File(tmpPath);
file.renameTo(tmp);//即使由于系统原因没有删掉文件,原文件也会因为文件名的改变而无法查找使用
return tmp.delete();
}
return false;
}
Android项目之SD卡
最新推荐文章于 2025-04-15 11:43:08 发布
212

被折叠的 条评论
为什么被折叠?



