Example:复制一个大型文件,为了节约内存,每次只读取500个字节。
源码:
NSString *homePath = NSHomeDirectory();
NSString *srcPath = [homePath stringByAppendingPathComponent:@"GitHub for Mac 176.zip"];
NSString *targetPath = [homePath stringByAppendingPathComponent:@"GitHub for Mac 176_bak.zip"];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success = [fileManager createFileAtPath:targetPath contents:nil attributes:nil];
if (success) {
NSLog(@"create success!");
}
NSFileHandle *inFile = [NSFileHandle fileHandleForReadingAtPath:srcPath];
NSFileHandle *outFile = [NSFileHandle fileHandleForWritingAtPath:targetPath];
NSDictionary *fileAttri = [fileManager attributesOfItemAtPath:srcPath error:nil];
NSNumber *fileSizeNum = [fileAttri objectForKey:NSFileSize];
BOOL isEnd = YES;
NSInteger readSize = 0;
NSInteger fileSize = [fileSizeNum longValue];
while (isEnd) {
NSInteger subLeng = fileSize - readSize;
NSData *data = nil;
if (subLeng < 500) {
isEnd = NO;
data = [inFile readDataToEndOfFile];
}else {
data = [inFile readDataOfLength:500];
readSize += 500;
[inFile seekToFileOffset:readSize];
}
[outFile writeData:data];
}