您的位置:首页 > 其它

oc 文件管理NSFileManager,文件读写NSFileHandle 文件复制

2015-05-27 20:44 393 查看


oc 文件管理NSFileManager,文件读写NSFileHandle ,设计一个文件管理类将一个文件复制到另一个文件,由于文件过大要求每次复制100长度,通过NSFileHandle 来操作

设计一个文件管理类将一个文件复制到另一个文件,由于文件过大要求每次复制100长度,通过NSFileHandle来操作,并通过代理模式打印出当前的赋值进度百分

main.m

#import <Foundation/Foundation.h>

#import "FileMaker.h"

int main(int argc,const char * argv[]) {

@autoreleasepool {

NSString * fromPath = [NSHomeDirectory()stringByAppendingPathComponent:@"desktop/name.txt"];

NSString * toPath = [NSHomeDirectory()stringByAppendingPathComponent:@"desktop/usa.txt"];

FileMaker * fileMaker = [[FileMakeralloc]init];

[fileMaker copyFileFromPath:fromPath toPath:toPath];

}

return 0;

}

FileMaker.m

#import "FileMaker.h"

@implementation FileMaker

设计一个文件管理类将一个文件复制到另一个文件,由于文件过大要求每次复制100长度,通过NSFileHandle来操作,并通过代理模式打印出当前的赋值进度百分比

- (void)copyFileFromPath:(NSString *)fromPath toPath:(NSString *)toPath{

// 1.1创建文件管理类

NSFileManager * manager = [NSFileManagerdefaultManager];

// 1.2通过键获取值(字符串)并转换为int类型,这样不用通过读数据就获取了文件的长度

// 通过文件管对象方法attributesOfItemAtPath:fromPath error:nil获得文件的一个字典

NSDictionary * dict = [manager attributesOfItemAtPath:fromPath error:nil];//此方法其中提供了文件容量的键值对

int totalSize = [[dict valueForKey:@"NSFileSize" ] intValue];

//1.3创建目标文件(在没有的情况下,若果不确定加判断是否存在,存在不创建,不存在创建)

[manager createFileAtPath:toPathcontents:nilattributes:nil];

NSLog(@"%@",dict);

// 2. 分别创建读、写管理者

NSFileHandle * readHandle = [NSFileHandlefileHandleForReadingAtPath:fromPath];

NSFileHandle * writeHandle = [NSFileHandlefileHandleForWritingAtPath:toPath];

设计一个文件管理类将一个文件复制到另一个文件,由于文件过大要求每次复制100长度,通过NSFileHandle来操作,并通过代理模式打印出当前的赋值进度百分比

// 3.循环读取源文件,并且写入目标文件

int per = 100;

int times = totalSize%100 ==0 ? totalSize/per :totalSize/per +1;

for (int i =0; i < times ; i++) {

[readHandleseekToFileOffset:per * i];

NSData * data = [readHandle readDataOfLength:per];

[writeHandleseekToEndOfFile];

[writeHandle writeData:data];

}

// 关闭文件

[writeHandlecloseFile];

[readHandlecloseFile];

}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: