/**
* 獲得系統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卡
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.