路径
1、相对路径
head.png :表示在当前目录中的文件head.png。
resource/head.png :表示resource目录中的文件head.png,resource在当前目录中。
2、绝对路径
/Users/Danny :以斜线(/)开始,斜线是根目录。
~Danny :代表用户Danny的主目录。
.
:表示当前目录
..
:表示父目录
文件
NSString *documentsPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *testDirPath=[documentsPath stringByAppendingPathComponent:@"test"];
//创建文件管理器的实例
NSFileManager *fm=[NSFileManager defaultManager];
//创建文件夹
NSError *error=nil;
if(![fm fileExistsAtPath:testDirPath])
{
bool createDirect=[fm createDirectoryAtPath:testDirPath withIntermediateDirectories:YES attributes:nil error:&error];
if(createDirect)
{
NSLog(@"create dir success. ->%@",testDirPath);
}
else{
NSLog(@"create dir failed %@, ",error.userInfo);
}
}
//添加文件
NSString *testfile01=[testDirPath stringByAppendingPathComponent:@"txt0.txt"];
if(![fm fileExistsAtPath:testfile01])
{
NSData *data=[@"hello world" dataUsingEncoding:NSUTF8StringEncoding];
if([fm createFileAtPath:testfile01 contents:data attributes:nil]){
NSLog(@"create file success.");
}
else{
NSLog(@"create file failed");
}
}
//文件copy
NSString *copiedfile=[testDirPath stringByAppendingPathComponent:@"copiedfile.txt"];
if(![fm fileExistsAtPath:copiedfile])
{
NSError *err;
bool isCopySuccess= [fm copyItemAtPath:testfile01 toPath:copiedfile error: &err];
if(isCopySuccess)
{
NSLog(@"copy file successfully.");
}
else{
NSLog(@"copy file failed, %@",error);
}
}
//判断两个文件是否一致
if([fm contentsEqualAtPath:testfile01 andPath:copiedfile])
{
NSLog(@"两个文件一致");
}else{
NSLog(@"两个文件不一致");
}
//重命名
NSString *newName=[testDirPath stringByAppendingPathComponent:@"newCopyFile.txt"];
if(![fm fileExistsAtPath:newName])
{
NSError *_err=nil;
if([fm moveItemAtPath:copiedfile toPath:newName error:&_err])
{
NSLog(@"rename success");
}
else{
NSLog(@"rename failed");
}
}
//获取文件大小
NSDictionary *attr= [fm attributesOfItemAtPath:newName error:nil];
for(NSString *tm in attr)
{
NSLog(@"属性 %@ = %@ ",tm,attr[tm]);
}
// 查看路径下有哪些文件
NSArray *ar= [fm contentsOfDirectoryAtPath:testDirPath error:NULL];
for(int i=0;i<ar.count;i++)
{
NSLog(@"---->%@",[ar objectAtIndex:i]);
}
//删除文件
NSError *err_remove=nil;
if([fm fileExistsAtPath:testfile01])
{
if([fm removeItemAtPath:testfile01 error:&err_remove])
{
NSLog(@"remove success");
}
else{
NSLog(@"remove fail");
}
}
//读取文件数据
NSData *data= [fm contentsAtPath:newName];
NSString *k=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"file content is: %@",k);