// 创建文件管理器
NSFileManager *fm=[NSFileManager defaultManager];
//获取路径
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; [fm changeCurrentDirectoryPath:documentsDirectory]; //获取文件路劲 NSString* path = [documentsDirectory stringByAppendingPathComponent:@"aaa.txt"]; //查找文件,如果不存在,就创建一个文件 if (![fm fileExistsAtPath:path]) { [fm createFileAtPath:path contents:nil attributes:nil];
} NSString *astr = @"aadsdafdsgdfgfd"; [astr writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
读取文件
// 创建文件管理器
NSFileManager *fm=[NSFileManager defaultManager];
//获取路径
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:]; [fm changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]];//扩张路径 //获取文件路劲 NSString* path = [documentsDirectory stringByAppendingPathComponent:@"aaa.txt"];//把文件名加在路径后面 NSString *s = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
self.aaa.text=s;
注意:在项目中获取文件路径
NSString *path=[[NSBundlemainBundle] pathForResource:self.plistofType:@"plist"];
在整个本地计算机上获取文件路径
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0];