IOS開發(fā) 沙盒中的文件操作

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);

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容