[关闭]
@fiy-fish 2015-07-19T18:08:19.000000Z 字数 1770 阅读 1380

day08-03-文件拷贝器

Objective-c


  1. // main.m
  2. // day08-03-文件拷贝器
  3. //
  4. // Created by Aaron on 15/7/10.
  5. // Copyright (c) 2015年 Aaron. All rights reserved.
  6. //
  7. #import <Foundation/Foundation.h>
  8. /*
  9. 自己封装一个单例类,实现一个拷贝器
  10. 功能:实现文件拷贝
  11. */
  12. #import "CopyManager.h"
  13. int main(int argc, const char * argv[]) {
  14. @autoreleasepool {
  15. CopyManager *manager = [CopyManager defaultManager];
  16. NSLog(@"%@",manager);
  17. // BOOL rec = [manager copyFileFromPath:@"/users/qianfeng/desktop/file1.txt" toPath:@"/users/qianfeng/desktop/file2.txt"];
  18. // NSLog(@"%@",rec?@"成功":@"失败");
  19. }
  20. return 0;
  21. }

  1. #import <Foundation/Foundation.h>
  2. @interface CopyManager : NSObject
  3. +(instancetype)defaultManager;
  4. -(BOOL)copyFileFromPath:(NSString *)oldPath toPath:(NSString *)newPath;
  5. @end

  1. #import "CopyManager.h"
  2. @implementation CopyManager
  3. //创建单列
  4. static CopyManager *manager = nil;
  5. //系统自己调用
  6. +(void)initialize
  7. {
  8. manager = [[self alloc] init];
  9. NSLog(@"我是初始化");
  10. }
  11. +(instancetype)defaultManager
  12. {
  13. return manager;
  14. }
  15. -(BOOL)copyFileFromPath:(NSString *)oldPath toPath:(NSString *)newPath
  16. {
  17. //判断源文件是否存在
  18. BOOL isExist = NO;
  19. BOOL isDir = NO;
  20. NSFileManager *manager = [NSFileManager defaultManager];
  21. isExist = [manager fileExistsAtPath:oldPath isDirectory:&isDir];
  22. if(isExist)
  23. {
  24. if(!isDir)
  25. {
  26. BOOL createSuc = [manager createFileAtPath:newPath contents:nil attributes:nil];
  27. if(createSuc)
  28. {
  29. NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:oldPath];
  30. NSFileHandle *writeHandle = [NSFileHandle fileHandleForWritingAtPath:newPath];
  31. //拿到文件属性
  32. NSDictionary *attributes = [manager attributesOfItemAtPath:oldPath error:nil];
  33. //得到文件大小
  34. NSInteger length = [attributes[NSFileSize] integerValue];
  35. while(length>0)
  36. {
  37. if(length > 100)
  38. {
  39. NSData *data = [readHandle readDataOfLength:100];
  40. [writeHandle writeData:data];
  41. length-=100;
  42. }
  43. else
  44. {
  45. NSData *data = [readHandle readDataToEndOfFile];
  46. [writeHandle writeData:data];
  47. length = 0;
  48. }
  49. }
  50. [writeHandle synchronizeFile];
  51. [writeHandle closeFile];
  52. [readHandle closeFile];
  53. return YES;
  54. }
  55. }
  56. }
  57. return NO;
  58. }
  59. @end
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注