1、獲取程序的Home目錄
NSString*path = NSHomeDirectory();
NSLog(@"path:%@",path);
打印結(jié)果:
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
真機(jī)上的目錄是:
2012-06-17 14:25:47.059 IosSandbox[4281:f803]/var/mobile/Applications/3B8EC78A-5EEE-4C2F-B0CB-4C3F02B996D2
可見,真機(jī)上的目錄是/var/mobile/Applications/這個(gè)目錄下的,和模擬器不一樣。這個(gè)是Home目錄,其他的子目錄和模擬器一樣。
2、獲取Document目錄
NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString*path=[pathsobjectAtIndex:0];
NSLog(@"path:%@",path);
打印結(jié)果:
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);
打印結(jié)果:
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);
打印結(jié)果:
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);
打印結(jié)果:
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:@"內(nèi)容",@"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);