一、IOS沙盒下获取文件路径的方式,常用的2种:
1、NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
2、NSString* docPath = [NSHomeDirectory() stringByAppendingPathComponent: @"Documents"];
二、IOS下沙盒下创建文件
1、NSString *filePath =[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/newfile.txt"];
2、NSString *filePath= [documentsDirectory stringByAppendingPathComponent:@"newfile.txt"];
结果为:/Documents/newfile.txt
三、IOS沙盒下创建目录
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *testDirectory = [documentsDirectory stringByAppendingPathComponent:@"test"];
// 创建目录
[fileManager createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];
四、IOS沙盒写入文件
1、可以用 NSFileManager的下列方法:
- (BOOL)createFileAtPath:(NSString *)path contents:(NSData *)data attributes:(NSDictionary *)attr;
2、 NSData
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile; (常用)
- (BOOL)writeToFile:(NSString *)path options:(NSUInteger)writeOptionsMask error:(NSError **)errorPtr;
五、IOS删除文件
用 NSFileManager方法[fileMgr removeItemAtPath:filePath2 error:&error]
//Removes the file or directory at the specified URL.
(BOOL)removeItemAtURL:(NSURL *)URL error:(NSError **)error
六、IOS沙盒读取文件
NSData *data = [fileManger contentsAtPath:myFilePath];//myFilePath是包含完整路径的文件名
或直接用NSData 的类方法:
NSData *data = [NSData dataWithContentOfPath:myFilePath];