首页 > 代码库 > OC基础:7.1 7.2 7.3 NSFileHandle 和 NSFileManager学习

OC基础:7.1 7.2 7.3 NSFileHandle 和 NSFileManager学习



复制一个文件:

 @autoreleasepool {
        NSString *homePah = NSHomeDirectory();
        NSLog(@"%@",homePah);
        NSString *srcPath = [homePah stringByAppendingPathComponent:@"iOS.pdf"];
        NSString *tagetPath = [homePah stringByAppendingPathComponent:@"iOS_bak.pdf"];
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL success = [fileManager createFileAtPath:tagetPath contents:nil attributes:nil];
        if (success) {
            NSLog(@"创建成功");
        }
        
        NSFileHandle *inFile = [NSFileHandle fileHandleForReadingAtPath:srcPath];
        NSFileHandle *outFile = [NSFileHandle fileHandleForWritingAtPath:tagetPath];
        
        NSDictionary *fileAttr = [fileManager attributesOfItemAtPath:srcPath error:nil];
        NSNumber *fileSizeNum = [fileAttr 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];
        }
        
        [outFile closeFile];
    }


OC基础:7.1 7.2 7.3 NSFileHandle 和 NSFileManager学习