iOS开发中我们会需要需要操作沙盒中的文件,创建文件夹,删除文件,获取文件大小,创建时间,修改时间,文件夹大小,删除具体文件,详细操作如下
创建文件夹
NSString *audioDir=[NSString stringWithFormat:@"%@/FlyElephant/", NSTemporaryDirectory()];
BOOL isDir=NO;
NSFileManager *fileManager=[NSFileManager defaultManager];
BOOL existed=[fileManager fileExistsAtPath:audioDir isDirectory:&isDir];
if (!(isDir == YES && existed == YES)){
[fileManager createDirectoryAtPath:audioDir withIntermediateDirectories:YES attributes:nil error:nil];
}
删除文件夹
NSString *audioDir=[NSString stringWithFormat:@"%@/FlyElephant/", NSTemporaryDirectory()];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:audioDir error:nil];
拷贝文件
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *fromPath = [[self composeDir] stringByAppendingString:@"keso.wav"];
NSString *toPath = [[self composeDir] stringByAppendingString:@"FlyElephant.wav"];
NSError *error;
[fileManager copyItemAtURL:[NSURL fileURLWithPath:fromPath] toURL:[NSURL fileURLWithPath:toPath] error:&error];
if (error) {
NSLog(@"Error:%@",error.description);
}
获取所有子文件
NSFileManager *fileManager=[NSFileManager defaultManager];
NSError *error=nil;
NSArray *childList=[fileManager contentsOfDirectoryAtPath:NSTemporaryDirectory() error:&error];
if (!error) {
NSLog(@"FlyElephant--%@--子文件目录:%@",NSTemporaryDirectory(),childList);
}
获取文件大小,创建时间,修改时间
for (NSInteger i=0; i<[childList count]; i++) {
NSString *fileName=[childList objectAtIndex:i];
if ([fileName hasSuffix:@"jpg"]) {
NSString *path=[NSTemporaryDirectory() stringByAppendingString:fileName];
NSError *pathError=nil;
NSDictionary *dict=[[NSFileManager defaultManager] attributesOfItemAtPath:path error:&pathError];
if (pathError==nil) {
NSLog(@"FlyElephant--%@",dict);
}
}
}
上面这个方法可以获取tmp文件目录中的jpg文件,具体的创建时间,我们可以根据dict中的key值获取,常用获取方法如下:
- (unsigned long long)fileSize;
- (nullable NSDate *)fileModificationDate;
- (nullable NSString *)fileType;
- (NSUInteger)filePosixPermissions;
- (nullable NSString *)fileOwnerAccountName;
- (nullable NSString *)fileGroupOwnerAccountName;
- (NSInteger)fileSystemNumber;
- (NSUInteger)fileSystemFileNumber;
- (BOOL)fileExtensionHidden;
- (OSType)fileHFSCreatorCode;
- (OSType)fileHFSTypeCode;
- (BOOL)fileIsImmutable;
- (BOOL)fileIsAppendOnly;
- (nullable NSDate *)fileCreationDate;
- (nullable NSNumber *)fileOwnerAccountID;
- (nullable NSNumber *)fileGroupOwnerAccountID;
基于以上的属性,我们可以获取特定目录下的特定类型文件的大小,计算出缓存的大小,清除缓存~