实例:
//
// main.m
// FileRead
//
// Created by 5016 on 13-12-17.
// Copyright (c) 2013年 dradon. All rights reserved.
//
#import <Foundation/Foundation.h>
/*
*断点copy
*/
void copyFile()
{
//读取文件
NSString *homePath = NSHomeDirectory();//获取根目录
NSString *srcPath = [homePath stringByAppendingPathComponent:@"Desktop/FileRead/objective-c.pdf"];//拼接文件路径
NSString *targetPath = [homePath stringByAppendingPathComponent:@"Desktop/FileRead/objective-c_OC.pdf"];//拼接文件路径
//1.新建文件管理器
NSFileManager *fileManager = [NSFileManager defaultManager];
//2.创建文件
BOOL success = [fileManager createFileAtPath:targetPath contents:nil attributes:nil];
if (success) {
NSLog(@"创建成功");
}
//3.获取文件长度大小
NSFileHandle *inFile = [NSFileHandle fileHandleForReadingAtPath:srcPath];
NSFileHandle *outFile = [NSFileHandle fileHandleForWritingAtPath:targetPath];
NSDictionary *fileAttrible = [fileManager attributesOfItemAtPath:srcPath error:nil];//获取文件上属性
NSLog(@"文件属性%@",fileAttrible);
NSNumber *fileSizeNum = [fileAttrible objectForKey:NSFileSize];
BOOL isEnd = NO;
NSInteger fileSize = [fileSizeNum longValue];
NSInteger readSize = 0;
NSAutoreleasePool *pool = nil;
int n = 0;
//循环断点copy
while (!isEnd) {
if (n%10 == 0) {//没10次释放一次
[pool release];
pool = [[NSAutoreleasePool alloc]init];
}
NSInteger subLen = fileSize - readSize;
NSData *data = nil;
if (subLen<500) {
isEnd = YES;
data = [inFile readDataToEndOfFile];//读到末尾
}else{
data = [inFile readDataOfLength:500];//每次读500
readSize += 500;
[inFile seekToFileOffset:readSize];//移动读的指针位置
}
//NSLog(@"data:%ld",[data retainCount]);
[outFile writeData:data];
n++;
}
[outFile closeFile];
[inFile closeFile];
NSLog(@"短点复制完毕");
}
int main(int argc, const char * argv[])
{
@autoreleasepool {
copyFile();
}
return 0;
}