//// main.m// 复制大型文件(一次读5K)//// Created by on 14-10-19.// Copyright (c) 2014年. All rights reserved.//#importint main(int argc, const char * argv[]) { @autoreleasepool { NSString *srcPath = @"/Users/wujiafeng/Downloads/A.tud"; NSString *targetPath = @"/Users/wujiafeng/Desktop/B.tud"; NSFileManager *fileManager = [NSFileManager defaultManager]; BOOL success = [fileManager createFileAtPath:targetPath contents:nil attributes:nil]; if (!success) { NSLog(@"创建文件失败"); } NSFileHandle *infile = [NSFileHandle fileHandleForReadingAtPath:srcPath]; NSFileHandle *outfile = [NSFileHandle fileHandleForWritingAtPath:targetPath];// 用attributesOfItemAtPath方法获取文件的属性// 获取文件的长度// 这里不要使用// [infile availableData];// 因为这个方法是“从设备或通道返回可用的数据”// 所以如果文件很大的话,那么程序占用资源会很多 NSDictionary *fileAttri = [fileManager attributesOfItemAtPath:srcPath error:nil]; NSNumber *fileSizeNum = [fileAttri objectForKey:NSFileSize]; BOOL isEnd = YES; NSInteger readSize = 0; NSInteger fileSize = [fileSizeNum longValue]; /* ====== 关闭ARC模式下的写法 =====*/ /* NSAutoreleasePool *pool = nil; int n = 0; while (isEnd) { if (n % 10 == 0) {// 循环10次,release一下自动释放池// 保证程序占用少量的内存 [pool release]; pool = [[NSAutoreleasePool alloc] init]; } NSData *data = nil;// 文件剩余的大小 NSInteger subSize = fileSize - readSize; if (subSize <= 5000) { isEnd = NO;// 如果源文件剩余读取大小少于5000字节,则直接读取到文件末尾即可 data = [infile readDataToEndOfFile]; } else { data = [infile readDataOfLength:5000]; readSize += 5000;// 将偏移量移动至刚才读取到的位置,以便下一次从偏移量开始读取 [infile seekToFileOffset:readSize]; } [outfile writeData:data]; n++; } */ /*===== 启动ARC模式下的写法 =====*/ int n = 0; while (isEnd) {// 这里的@autoreleasepool{}是写在循环内的,不要将其写在循环外 @autoreleasepool { NSData *data = nil; NSInteger subSize = fileSize - readSize; if (subSize <= 5000) { isEnd = NO; data = [infile readDataToEndOfFile]; } else { data = [infile readDataOfLength:5000]; readSize += 5000; [infile seekToFileOffset:readSize]; } [outfile writeData:data]; n++; } } [infile closeFile]; [outfile closeFile]; NSLog(@"文件复制完毕"); } return 0;}