您的位置:首页 > 其它

指定字节拷贝文件

2015-11-06 21:14 351 查看
#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: