OC文件操作之按字节拷贝文件

来源:互联网 发布:drums架子鼓软件下载 编辑:程序博客网 时间:2024/05/22 13:07

思路是这样的:
1.首先你要找到需要拷贝的文件的路径,指定要拷贝的路径,这个路径可能不存在,所以你就要先判断是否存在,不存在还要创建。
2.对源文件进行读取,首先求出文件大小,然后就是一个循环按字节读取,写入。当剩余长度小于要按照的字节时,直接读取到文件的末尾;否则就按字节读取写入。里面有两个重要的方法 :
//跳转到指定的的文件节点 [oldHandle seekToFileOffset:readLength];
//读取若干长度字节data=[oldHandle readDataOfLength:size];

#import <Foundation/Foundation.h>#import "SizeCopy.h"int main(int argc, const char * argv[]) {    @autoreleasepool {SizeCopy *began=[[SizeCopy alloc]init];//将文件按照10个字节一读取的方式复制[began accordingByteCopy:10000];    }    return 0;}

下面创建一个SizeCopy类
SizeCopy.h

#import <Foundation/Foundation.h>@interface SizeCopy : NSObject//根据传进来的数值决定每次分多大进行拷贝-(void)accordingByteCopy:(NSInteger)size;@end

SizeCopy.m

#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
0 0
原创粉丝点击