Object-C 学习笔记(二十六)--- 文件断点拷贝

实例:

//
//  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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值