zoukankan      html  css  js  c++  java
  • 指定字节拷贝文件

    #import "SizeCopy.h"

    @implementation SizeCopy

    -(void)accordingByteCopy:(NSInteger)size
    {
        //获取桌面上的文件路径,以便拷贝
        NSString *oldPath=@"/Users/scjy/Desktop/video.mp4";
        //指定将要拷贝到哪里
        NSString *newPath=@"/Users/scjy/Desktop/movie.mp4";
        //创建文件管理者,准备创建文件
        NSFileManager *fileManager=[NSFileManager defaultManager];
        //判断将要创建的文件是不是已经存在
        BOOL isHave=[fileManager fileExistsAtPath:newPath];
        if (!isHave) {
            //不存在的话,开始执行创建,并判断是不是创建成功
            BOOL isSec=[fileManager createFileAtPath:newPath contents:nil attributes:nil];
            if (isSec) {
                NSLog(@"文件创建成功,开始复制");
            }
            else
            {
                return;
            }
        }
       
        NSFileHandle *oldHandle=[NSFileHandle fileHandleForReadingAtPath:oldPath];//读取文件的handle
        NSFileHandle *newHandle=[NSFileHandle fileHandleForUpdatingAtPath:newPath];//写入文件的handle
       
        //表示文件已经读取过,指针已经移动到数据的最后一位
        //NSLog(@"%ld",[oldHandle availableData].length);--有准确值
        //NSLog(@"%ld",[oldHandle availableData].length);--值为0
       
        //attributesOfItemAtPath获取文件的大小,内容等方法
        NSDictionary *dictionary=[fileManager attributesOfItemAtPath:oldPath error:nil];
        //返回文件的有效内容大小
        NSNumber *lenNum=[dictionary valueForKey:NSFileSize];
        NSInteger fileLength=[lenNum integerValue];//转成基本数据类型
       
        NSInteger readLength=0;
        BOOL isEnd=NO;
       
        while (!isEnd) {
            NSData *data=nil;
           
            //获取剩余未拷贝文件长度
            NSInteger subLegth=fileLength-readLength;
           
            //判断是不是最后一次节点复制文件
            if (subLegth<size) {
                isEnd=YES;
                [oldHandle readDataToEndOfFile];//读取到文件末尾
                NSLog(@"拷贝完成:100%@",@"%");
            }
            else
            {
                data=[oldHandle readDataOfLength:size];//读取若干字节
                readLength+=size;
               
                //跳转到拷贝结束的文件节点
                [oldHandle seekToFileOffset:readLength];
               
                //计算拷贝比例
                NSNumber *readNum=[NSNumber numberWithInteger:readLength];
                NSLog(@"正在拷贝:%.3f%@",[readNum doubleValue]/[lenNum doubleValue]*100,@"%");
            }
           
            [newHandle writeData:data];//写入文件
           
           
        }
       
        [oldHandle closeFile];//关闭文件
        [newHandle closeFile];
    }


    @end
  • 相关阅读:
    python文件操作,读取,修改,合并
    LWIP学习之流程架构
    嵌入式网络笔记
    AD17笔记
    STM32之VCP1/VCAP2引脚的处理
    AD中添加中文字符丝印的方法:
    磁珠与电感
    稳压二极管选型
    TVS选型
    光耦的使用
  • 原文地址:https://www.cnblogs.com/shuxiachahu123/p/4943656.html
Copyright © 2011-2022 走看看