1 - (void)viewDidLoad 2 { 3 [super viewDidLoad]; 4 // Do any additional setup after loading the view. 5 self.title = @"拷贝文件到Sandbox"; 6 7 //文件类型 8 NSString * docPath = [[NSBundle mainBundle] pathForResource:@"save1" ofType:@"dat"]; 9 10 // 沙盒Documents目录 11 // NSString * appDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 12 13 // 沙盒Library目录 14 NSString * appDir = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject]; 15 //appLib Library/Caches目录 16 NSString *appLib = [appDir stringByAppendingString:@"/Caches"]; 17 18 BOOL filesPresent = [self copyMissingFile:docPath toPath:appLib]; 19 if (filesPresent) { 20 NSLog(@"OK"); 21 } 22 else 23 { 24 NSLog(@"NO"); 25 } 26 27 // 创建文件夹 28 NSString *createDir = [NSHomeDirectory() stringByAppendingString:@"/test"]; 29 [self createFolder:createDir]; 30 31 // 把文件拷贝到Test目录 32 BOOL filesPresent1 = [self copyMissingFile:docPath toPath:createDir]; 33 if (filesPresent1) { 34 NSLog(@"OK"); 35 } 36 else 37 { 38 NSLog(@"NO"); 39 } 40 41 42 } 43 44 /** 45 * @brief 把Resource文件夹下的save1.dat拷贝到沙盒 46 * 47 * @param sourcePath Resource文件路径 48 * @param toPath 把文件拷贝到XXX文件夹 49 * 50 * @return BOOL 51 */ 52 - (BOOL)copyMissingFile:(NSString *)sourcePath toPath:(NSString *)toPath 53 { 54 BOOL retVal = YES; // If the file already exists, we'll return success… 55 NSString * finalLocation = [toPath stringByAppendingPathComponent:[sourcePath lastPathComponent]]; 56 if (![[NSFileManager defaultManager] fileExistsAtPath:finalLocation]) 57 { 58 retVal = [[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:finalLocation error:NULL]; 59 } 60 return retVal; 61 } 62 63 /** 64 * @brief 创建文件夹 65 * 66 * @param createDir 创建文件夹路径 67 */ 68 - (void)createFolder:(NSString *)createDir 69 { 70 BOOL isDir = NO; 71 NSFileManager *fileManager = [NSFileManager defaultManager]; 72 BOOL existed = [fileManager fileExistsAtPath:createDir isDirectory:&isDir]; 73 if ( !(isDir == YES && existed == YES) ) 74 { 75 [fileManager createDirectoryAtPath:createDir withIntermediateDirectories:YES attributes:nil error:nil]; 76 } 77 }