@fiy-fish
2015-07-19T18:08:19.000000Z
字数 1770
阅读 1380
Objective-c
// main.m
// day08-03-文件拷贝器
//
// Created by Aaron on 15/7/10.
// Copyright (c) 2015年 Aaron. All rights reserved.
//
#import <Foundation/Foundation.h>
/*
自己封装一个单例类,实现一个拷贝器
功能:实现文件拷贝
*/
#import "CopyManager.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
CopyManager *manager = [CopyManager defaultManager];
NSLog(@"%@",manager);
// BOOL rec = [manager copyFileFromPath:@"/users/qianfeng/desktop/file1.txt" toPath:@"/users/qianfeng/desktop/file2.txt"];
// NSLog(@"%@",rec?@"成功":@"失败");
}
return 0;
}
#import <Foundation/Foundation.h>
@interface CopyManager : NSObject
+(instancetype)defaultManager;
-(BOOL)copyFileFromPath:(NSString *)oldPath toPath:(NSString *)newPath;
@end
#import "CopyManager.h"
@implementation CopyManager
//创建单列
static CopyManager *manager = nil;
//系统自己调用
+(void)initialize
{
manager = [[self alloc] init];
NSLog(@"我是初始化");
}
+(instancetype)defaultManager
{
return manager;
}
-(BOOL)copyFileFromPath:(NSString *)oldPath toPath:(NSString *)newPath
{
//判断源文件是否存在
BOOL isExist = NO;
BOOL isDir = NO;
NSFileManager *manager = [NSFileManager defaultManager];
isExist = [manager fileExistsAtPath:oldPath isDirectory:&isDir];
if(isExist)
{
if(!isDir)
{
BOOL createSuc = [manager createFileAtPath:newPath contents:nil attributes:nil];
if(createSuc)
{
NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:oldPath];
NSFileHandle *writeHandle = [NSFileHandle fileHandleForWritingAtPath:newPath];
//拿到文件属性
NSDictionary *attributes = [manager attributesOfItemAtPath:oldPath error:nil];
//得到文件大小
NSInteger length = [attributes[NSFileSize] integerValue];
while(length>0)
{
if(length > 100)
{
NSData *data = [readHandle readDataOfLength:100];
[writeHandle writeData:data];
length-=100;
}
else
{
NSData *data = [readHandle readDataToEndOfFile];
[writeHandle writeData:data];
length = 0;
}
}
[writeHandle synchronizeFile];
[writeHandle closeFile];
[readHandle closeFile];
return YES;
}
}
}
return NO;
}
@end