1、获取程序的Home目录
NSString*path = NSHomeDirectory();
NSLog(@"path:%@",path);
打印结果:
2012-07-11 11:18:16.291 TestProject[2387:f803] path:/Users/username/Library/Application Support/iPhone Simulator/5.1/Applications/BAE91297-A4C6-4DDC-A9DA-7B790B36CE7A
真机上的目录是:
2012-06-17 14:25:47.059 IosSandbox[4281:f803]/var/mobile/Applications/3B8EC78A-5EEE-4C2F-B0CB-4C3F02B996D2
可见,真机上的目录是/var/mobile/Applications/这个目录下的,和模拟器不一样。这个是Home目录,其他的子目录和模拟器一样。
2、获取Document目录
NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString*path=[pathsobjectAtIndex:0];
NSLog(@"path:%@",path);
打印结果:
2012-07-11 11:21:22.879 TestProject[2417:f803] path:/Users/username/Library/Application Support/iPhone Simulator/5.1/Applications/BAE91297-A4C6-4DDC-A9DA-7B790B36CE7A/Documents
3、获取Cache目录
NSArray*paths=NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
NSString*path=[pathsobjectAtIndex:0];
NSLog(@"path:%@",path);
打印结果:
2012-07-11 11:13:36.162 TestProject[2310:f803] path:/Users/username/Library/Application Support/iPhone Simulator/5.1/Applications/BAE91297-A4C6-4DDC-A9DA-7B790B36CE7A/Library/Caches
4、获取Library目录
NSArray*paths=NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES);
NSString*path=[pathsobjectAtIndex:0];
NSLog(@"path:%@",path);
打印结果:
2012-07-11 11:14:41.138 TestProject[2337:f803] path:/Users/username/Library/Application Support/iPhone Simulator/5.1/Applications/BAE91297-A4C6-4DDC-A9DA-7B790B36CE7A/Library
5、获取Tmp目录
NSString*path=NSTemporaryDirectory();
NSLog(@"%@", path);
打印结果:
2012-07-11 11:16:09.438 TestProject[2358:f803] path:/var/folders/hj/8sgyk0f555l1z_n95p2b2kp00000gn/T/
6、写入文件
NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *docDir = [paths objectAtIndex:0];
if(!docDir) {
NSLog(@"Documents 目录未找到");
}
NSArray *array = [[NSArray alloc]initWithObjects:@"内容",@"content",nil];
NSString *filePath = [docDir stringByAppendingPathComponent:@"testFile.txt"];
[array writeToFile:filePath atomically:YES];
7、读取文件
NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *filePath = [docDir stringByAppendingPathComponent:@"testFile.txt"];
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
NSLog(@"%@",array);