1 - (nullable NSDirectoryEnumerator<NSURL *> *)enumeratorAtURL:(NSURL *)url includingPropertiesForKeys:(nullable NSArray<NSURLResourceKey> *)keys options:(NSDirectoryEnumerationOptions)mask errorHandler:(nullable BOOL (^)(NSURL *url, NSError *error))handler API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
參數(shù)一: 目錄地址
參數(shù)二:從子目錄的URL中預(yù)取和緩存的資源屬性,如果為空則只返回子目錄的地址,沒有屬性
參數(shù)三:遍歷時(shí)選項(xiàng),如不遍歷隱藏文件NSDirectoryEnumerationSkipsHiddenFiles,不遍歷子文件夾NSDirectoryEnumerationSkipsSubdirectoryDescendants
2 獲取目錄下子文件的地址和子文件的屬性 (來自SDImageCache下 deleteOldFilesWithCompletionBlock方法)
//獲取地址
NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
//設(shè)置預(yù)取的屬性
NSArray<NSString *> *resourceKeys = @[NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey];
// 獲取地址和文件屬性
NSDirectoryEnumerator *fileEnumerator = [self.fileManager enumeratorAtURL:diskCacheURL
includingPropertiesForKeys:resourceKeys
options:NSDirectoryEnumerationSkipsHiddenFiles
errorHandler:NULL];
//遍歷
for (NSURL *fileURL in fileEnumerator) {
NSError *error;
NSDictionary<NSString *, id> *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:&error];
NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
}
3 判斷路徑下是否存在文件并且是文件夾
- (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(nullable BOOL *)isDirectory;
參數(shù)一:路徑
參數(shù)二:是不是文件夾
4 創(chuàng)建一個(gè)文件夾的時(shí)候,判斷文件夾是否存在,如果存在文件則把文件刪除,如果不存在文件則創(chuàng)建文件夾
+ (NSString *)directoryPathWithBasePath:(NSString *)basePath relativePath:(NSString *)relativePath {
NSString *directoryPath = nil;
if (!!basePath.length) {
directoryPath = [basePath stringByAppendingPathComponent:relativePath];
BOOL needCreateDirectory = YES;
BOOL isDirectory = NO;
if ([[NSFileManager defaultManager] fileExistsAtPath:directoryPath isDirectory:&isDirectory]) {
if (isDirectory) {
needCreateDirectory = NO;
} else {
[[NSFileManager defaultManager] removeItemAtPath:directoryPath error:nil];
}
}
if (needCreateDirectory) {
[[NSFileManager defaultManager] createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:nil];
}
}
return directoryPath;
}
在我寫做測(cè)試的時(shí)候發(fā)現(xiàn),蘋果部分情況下會(huì)自動(dòng)把文件的擴(kuò)展名加上,如有名字為a的圖片,它的地址是 **/a.png
5 - (nullable NSArray<NSString *> *)subpathsAtPath:(NSString *)path;
返回一個(gè)數(shù)組,數(shù)組包含 path路徑下所有的子文件和遞歸所有字文件的路徑的地址
缺點(diǎn)不能過濾隱藏文件,不能配置是否遍歷子文件,所以建議上面的第一種方法
6 獲取當(dāng)前App下可用的硬盤大小
+ (NSNumber *)freeDiskSpace
{
NSDictionary *fattributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil];
return [fattributes objectForKey:NSFileSystemFreeSize];
}
7 獲取手機(jī)的總硬盤大小
#include <sys/mount.h>
+ (UInt64)totalDiskSpaceSize {
struct statfs tStats;
statfs("/var", &tStats);
return (tStats.f_blocks * tStats.f_bsize);
}