NSFileManager&NSFileHandle

`
NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"source" ofType:@"pdf"];
//创建用于写入的目标文件
NSString *targetPath = [self.documentsPath stringByAppendingPathComponent:@"target.pdf"];

BOOL success = [[NSFileManager defaultManager] createFileAtPath:targetPath contents:nil attributes:nil];
if (success) {
    NSLog(@"目标空PDF文件创建成功");
}else{
    NSLog(@"目标空PDF文件创建失败");
}
NSFileHandle *sourceHandle = [NSFileHandle fileHandleForReadingAtPath:sourcePath];
NSFileHandle *targetHandle = [NSFileHandle fileHandleForWritingAtPath:targetPath];

//通过while循环,每次写入一部分数据,知道全部写入完成
BOOL notEND = YES;
//存储当前已经读取的数量
NSInteger readSize = 0;
//每次读入的字节大小
NSInteger sizePerTime = 5000;
//获取文件总长度
NSDictionary *attr = [[NSFileManager defaultManager] attributesOfItemAtPath:sourcePath error:nil];
NSLog(@"attr:%@",attr);
NSNumber *sizeNumber = [attr objectForKey:NSFileSize];
NSInteger fileToltalNum = sizeNumber.integerValue;
//记录循环的次数,表示读取了源文件多少次
int count = 0;
while (notEND) {
    NSInteger leftSize = fileToltalNum - readSize;
    NSData *data = nil;
    //如果剩下的超过5000,则读5000,如果剩下的少于5000,则读到结尾
    
    if (leftSize >= sizePerTime) {
        data = [sourceHandle readDataOfLength:sizePerTime];
        //读完5000以后修改已读的数量
        readSize += sizePerTime;
        //移动读取源文件的指针到新的位置
        [sourceHandle seekToFileOffset:readSize];
        
    }else{
        //把剩余数据读出来
        data = [sourceHandle readDataToEndOfFile];
        //把还没读完设置为NO;
        notEND = NO;
    }
    //把data写入目标文件
    [targetHandle writeData:data];
    //读写次数加1
    count +=1;
}

[sourceHandle closeFile];
[targetHandle closeFile];
NSLog(@"总共读了%d次",count);

`

你可能感兴趣的:(NSFileManager&NSFileHandle)