删除文件
RemoveFile.m
#import "RemoveFile.h"
@implementation RemoveFile
-(void)removefile
{
//删除文件
NSString *homePath = NSHomeDirectory();//获取目录的路径
/*
创建文件管理
*/
NSFileManager *manager = [NSFileManager defaultManager];
NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents/file.text"];
//删除之前需要判断这个文件是否存在
BOOL isExist = [manager fileExistsAtPath:filePath];//判断文件是否存在
if(isExist){
BOOL sucess4 = [manager removeItemAtPath:filePath error:nil];//删除文件
if(sucess4){
NSLog(@"删除成功");
}else{
NSLog(@"删除失败");
}
}
}
@end
移动文件
MoveFile.m
#import "MoveFile.h"
@implementation MoveFile
-(void)movefile
{
//移动文件
NSString *homePath = NSHomeDirectory();//获取目录的路径
//创建文件管理器
NSFileManager *manager = [NSFileManager defaultManager];
//NSFileManager中没有提供重命名的方法,所以我们可以借助移动的api进行操作
// 把filePath移动到targetPath目录中
//在沙盒目录中创建一个文件file.text
NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents/file.text"];
NSString *targetPath = [homePath stringByAppendingPathComponent:@"Documents/file/file2.text"];
BOOL sucess2 = [manager moveItemAtPath:filePath toPath:targetPath error:nil];
if(sucess2) {
NSLog(@"移动成功");
}else{
NSLog(@"移动失败");
}
}
@end
===========================================================================创建文件夹
NewFolder.m
#import "NewFolder.h"
@implementation NewFolder
-(void)newfile
{
//创建文件夹
NSString *homePath = NSHomeDirectory();//获取目录的路径
//创建文件管理器
NSFileManager *manager = [NSFileManager defaultManager];
NSString *filePaths = [homePath stringByAppendingPathComponent:@"Documents/file"];
NSError *error;
//需要传递一个创建失败的指针对象,记录创建失败的信息
BOOL success1 = [manager createDirectoryAtPath:filePaths withIntermediateDirectories:YES attributes:nil error:&error];
//将attributes参数设置为nil,这样虽然能够创建出目录,但是在一些特殊场景下(比如iPhone的apps)所创建的目录的属性往往不是我们期望的,因而导致目录的读写失败等问题。其实通过设置attributes参数,这个接口可以完成我们的期望。
if(!success1){
NSLog(@"创建失败");
}else{
NSLog(@"创建成功");
}
}
@end
创建文件
NewFile.m
#import "NewFile.h"
@implementation NewFile
-(void)newfile
{
//创建文件
NSString *homePath = NSHomeDirectory();//获取目录的路径
//在沙盒目录中创建一个文件file.text
NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents/file.text"];
//NSFileManager是单例模式,所以不能使用alloc+init
//创建文件管理器
NSFileManager *manager = [NSFileManager defaultManager];
NSString *str = @"啦啦啦啦啦啦";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
//参数:文件路径、文件内容、文件的属性
BOOL sucess = [manager createFileAtPath:filePath contents:data attributes:nil];
if(sucess){
NSLog(@"文件创建成功");
}else{
NSLog(@"文件创建失败");
}
}
@end
获取文件的属性
GetFile.m
#import "GetFile.h"
@implementation GetFile
-(void)gainfile
{
//--------------------获取文件的属性
NSString *homePath = NSHomeDirectory();//获取目录的路径
NSFileManager *manager = [NSFileManager defaultManager];
NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents/file.text"];
NSDictionary *dic = [manager attributesOfItemAtPath:filePath error:nil];
NSLog(@"%@",dic);//通过打印我们就可以查看文件属性的一些key属性一般是NSDictionary
}
@end