QNFile.m 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. //
  2. // QNFile.m
  3. // QiniuSDK
  4. //
  5. // Created by bailong on 15/7/25.
  6. // Copyright (c) 2015年 Qiniu. All rights reserved.
  7. //
  8. #import "QNFile.h"
  9. #import "QNResponseInfo.h"
  10. @interface QNFile ()
  11. @property (nonatomic, readonly) NSString *filepath;
  12. @property (nonatomic) NSData *data;
  13. @property (readonly) int64_t fileSize;
  14. @property (readonly) int64_t fileModifyTime;
  15. @property (nonatomic) NSFileHandle *file;
  16. @end
  17. @implementation QNFile
  18. - (instancetype)init:(NSString *)path
  19. error:(NSError *__autoreleasing *)error {
  20. if (self = [super init]) {
  21. _filepath = path;
  22. NSError *error2 = nil;
  23. NSDictionary *fileAttr = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:&error2];
  24. if (error2 != nil) {
  25. if (error != nil) {
  26. *error = error2;
  27. }
  28. return self;
  29. }
  30. _fileSize = [fileAttr fileSize];
  31. NSDate *modifyTime = fileAttr[NSFileModificationDate];
  32. int64_t t = 0;
  33. if (modifyTime != nil) {
  34. t = [modifyTime timeIntervalSince1970];
  35. }
  36. _fileModifyTime = t;
  37. NSFileHandle *f = nil;
  38. NSData *d = nil;
  39. //[NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:&error] 不能用在大于 200M的文件上,改用filehandle
  40. // 参见 https://issues.apache.org/jira/browse/CB-5790
  41. if (_fileSize > 16 * 1024 * 1024) {
  42. f = [NSFileHandle fileHandleForReadingAtPath:path];
  43. if (f == nil) {
  44. if (error != nil) {
  45. *error = [[NSError alloc] initWithDomain:path code:kQNFileError userInfo:nil];
  46. }
  47. return self;
  48. }
  49. } else {
  50. d = [NSData dataWithContentsOfFile:path options:NSDataReadingMappedIfSafe error:&error2];
  51. if (error2 != nil) {
  52. if (error != nil) {
  53. *error = error2;
  54. }
  55. return self;
  56. }
  57. }
  58. _file = f;
  59. _data = d;
  60. }
  61. return self;
  62. }
  63. - (NSData *)read:(long)offset
  64. size:(long)size {
  65. if (_data != nil) {
  66. return [_data subdataWithRange:NSMakeRange(offset, (unsigned int)size)];
  67. }
  68. [_file seekToFileOffset:offset];
  69. return [_file readDataOfLength:size];
  70. }
  71. - (NSData *)readAll {
  72. return [self read:0 size:(long)_fileSize];
  73. }
  74. - (void)close {
  75. if (_file != nil) {
  76. [_file closeFile];
  77. }
  78. }
  79. - (NSString *)path {
  80. return _filepath;
  81. }
  82. - (int64_t)modifyTime {
  83. return _fileModifyTime;
  84. }
  85. - (int64_t)size {
  86. return _fileSize;
  87. }
  88. @end