复制文件: 节约内存 每次读取5k

    

         NSString *homePath = NSHomeDirectory();//获得根目录
            NSString *filePath = [homePath stringByAppendingPathComponent: @"/Movies/wp.MP4"];//获得源文件路径
            NSString *targetPath = [homePath stringByAppendingPathComponent: @"/Documents/wpvdisk.MP4"];//获得目标文件路径
//获得文件的大小; NSFileManager *fileManage = [NSFileManager defaultManager]; if ([fileManage fileExistsAtPath: filePath] == NO) { NSLog(@"file not exist"); return 1; } BOOL succeed = [fileManage createFileAtPath: targetPath contents: nil attributes: nil]; if (succeed) { NSLog(@"创建成功..."); } NSFileHandle *srcHandle = [NSFileHandle fileHandleForReadingAtPath: filePath];//将通道插入源文件 NSFileHandle *targetHandle = [NSFileHandle fileHandleForUpdatingAtPath: targetPath];//讲通道插入目标文件 NSInteger readLength = 0;//初始化读取的字节数 NSDictionary *fileAttributes = [fileManage attributesOfItemAtPath:filePath error:nil];//获得文件属性 NSInteger fileSize = [[fileAttributes objectForKey: NSFileSize] longValue];//获得文件的大小

BOOL isEnd = YES; NSData *data = nil; NSAutoreleasePool *pool = nil; int i = 0; while (isEnd) { if (i == 10) {//5mb清楚一次内存 [pool release]; pool = [[NSAutoreleasePool alloc] init]; } NSInteger subLength = fileSize - readLength; if (subLength < 5000) {//长度小于5000的就把剩下的读完吧. isEnd = NO; data = [srcHandle readDataToEndOfFile]; }else{ data = [srcHandle readDataOfLength: 5000]; readLength += 5000; [srcHandle seekToFileOffset: readLength]; } [targetHandle writeData: data]; i++; } [srcHandle closeFile]; [targetHandle closeFile]; NSLog(@"Copy is over!");

            

如果没有关闭ARC的会自动报错,建议关闭ARC. 

原文地址:https://www.cnblogs.com/mohe/p/2983250.html