文件操作
#import <Foundation/Foundation.h>
#define PATH @"/Users/chanbin/Desktop/Class7Test"
#define PATH1 @"/Users/chanbin/Desktop/Class7Test/a0.txt"
#define PATH2 @"/Users/chanbin/Desktop/"
int main(int argc,constchar * argv[])
{
@autoreleasepool {
/*
NSFileManager:文件管理器 单例
作用:创建移动删除拷贝文件或文件夹,读取文件属性
*/
//获取文件管理器
NSFileManager *manager =[NSFileManager defaultManager];
NSError * error =nil;
BOOL flag;
//文件是否存在
[manager fileExistsAtPath:PATH isDirectory:&flag];
if (flag)
NSLog(@"file exits!");
//否则创建一个文件夹
else
[manager createDirectoryAtPath:PATH withIntermediateDirectories:NO attributes:nil error:&error];
//删除文件夹
// [manager removeItemAtPath:PATH error:&error];
// if (error) {
// NSLog(@"error is %@",error);
// }
for(int i =0; i<10;i++)
{
NSString *filename = [NSString stringWithFormat:PATH@"/a%i.txt",i];
if(![manager fileExistsAtPath:filename])
[manager createFileAtPath:filenamecontents:[filenamedataUsingEncoding:NSUTF8StringEncoding]attributes:nil];
//contains:是否需要附加数据 attributes:是否程序要创建子目录
}
//读取文件大小
//将指定文件的属性读取到字典当中
NSDictionary *dic =[manager attributesOfItemAtPath:
[NSStringstringWithFormat:PATH@"/a%i.txt",0]error:nil];
//获取大小 NSMumber
NSLog(@"%@",[dicobjectForKey:NSFileSize]);
//浅度遍历 :目录下所有文件存储在数组中
NSArray *arr1 = [manager contentsOfDirectoryAtPath:PATH error:nil];
NSLog(@"arr1 is %@",arr1);
//深度遍历 :
NSArray *arr2 = [manager subpathsOfDirectoryAtPath:PATH error:nil];
NSLog(@"%@",arr2);
float count =0;
for (int i =0; i<arr2.count; i++) {
NSString * s = [NSString stringWithFormat:PATH@"/%@",arr2[i]];
if (([arr2[i] rangeOfString:@"."].length!=0)||([arr2[i] rangeOfString:@"Store"].length )!=0) {
NSDictionary *dic = [manager attributesOfItemAtPath:s error:nil];
count += [[dic objectForKey:NSFileSize]floatValue];
}
}
NSLog(@"%.1f",count);
NSLog(@"%li,%li",[@"aaa/a2.txt" rangeOfString:@"txt"].location,[@"aaa/a2.txt" rangeOfString:@"txt"].length
);
//拷贝文件 源地址 目标地址
if ([manager fileExistsAtPath:PATH1]) {
[manager copyItemAtPath:PATH1toPath:[NSStringstringWithFormat:@"%@_BAK",PATH1]error:&error];
if (error) {
NSLog(@"error %@",error);
}else{
NSLog(@"copy success!");
}
}
//拷贝目录
[manager moveItemAtPath:PATHtoPath:PATH2@"/Text"error:&error];
if (error) {
NSLog(@"error %@",error);
}
elseNSLog(@"move success");
//删除
[manager removeItemAtPath:PATH1error:&error];
if (error) {
NSLog(@"%@",error);
}
elseNSLog(@"remove success");
}
return0;
}