IOS项目开发中的文件和文件夹操作

  1 + (NSFileManager *)getNSFileManager
  2 {
  3     // iNSFileManager是一个静态变量
  4     if (!iNSFileManager)
  5     {
  6         iNSFileManager = [NSFileManager defaultManager];
  7     }
  8     return iNSFileManager;
  9 }
 10 
 11 #pragma mark 判断文件是否存在
 12 
 13 + (BOOL)fileExistsAtPath:(NSString *)aPath
 14 {
 15     BOOL result = NO;
 16     if (aPath)
 17     {
 18         result = [[self getNSFileManager] fileExistsAtPath:aPath];
 19         
 20     }
 21     return result;
 22 }
 23 
 24 + (BOOL)fileExistsAtDocumentsWithFileName:(NSString *)aFileName{
 25     BOOL result = NO;
 26     if (aFileName)
 27     {
 28         NSString *fullFileName = [self getFullDocumentPathWithName:aFileName];
 29         WALog(fullFileName);
 30         
 31         result = [[self getNSFileManager] fileExistsAtPath:fullFileName];
 32     }
 33     return result;
 34 }
 35 
 36 
 37 #pragma mark 判断文件夹是否存在
 38 + (BOOL)dirExistsAtPath:(NSString *)aPath
 39 {
 40     BOOL isDir = NO;
 41     BOOL result = [[self getNSFileManager] fileExistsAtPath:aPath
 42                                                 isDirectory:&isDir];
 43     return result && isDir;
 44 }
 45 
 46 #pragma mark 获取上级目录
 47 + (NSString *) getParentPath:(NSString *)aPath
 48 {
 49     return [aPath stringByDeletingLastPathComponent];
 50     
 51 }
 52 
 53 #pragma mark 创建目录的上级目录
 54 + (BOOL)createParentDirectory:(NSString *)aPath
 55 {
 56     //存在上级目录,并且上级目录不存在的创建所有的上级目录
 57     BOOL result = NO;
 58     NSString *parentPath = [self getParentPath:aPath];
 59     if (parentPath && ![self dirExistsAtPath:parentPath])
 60     {
 61         result = [[self getNSFileManager] createDirectoryAtPath:parentPath
 62                                     withIntermediateDirectories:YES
 63                                                      attributes:nil
 64                                                           error:nil];
 65     }
 66     else if ([self dirExistsAtPath:parentPath]){
 67         result = YES;
 68     }
 69     return result;
 70 }
 71 
 72 #pragma mark 创建目录
 73 + (BOOL)createPath:(NSString *)aPath
 74 {
 75     NSFileManager *tempFileManager = [self getNSFileManager];
 76     BOOL result = NO;
 77     result = [self createParentDirectory:aPath];
 78     if (result)
 79     {
 80         result = [tempFileManager createDirectoryAtPath:aPath
 81                             withIntermediateDirectories:YES
 82                                              attributes:nil
 83                                                   error:nil];
 84         
 85     }
 86     return result;
 87 }
 88 
 89 #pragma mark 目录下创建文件
 90 + (BOOL)createFileWithPath:(NSString *)aPath content:(NSData *)aContent
 91 {
 92     NSFileManager *tempFileManager = [self getNSFileManager];
 93     BOOL result = NO;
 94     result = [self createParentDirectory:aPath];
 95     if (result)
 96     {
 97         result = [tempFileManager createFileAtPath:aPath
 98                                           contents:aContent
 99                                         attributes:nil];
100     }
101     return result;
102 }
103 
104 #pragma mark documents下创建文件
105 + (BOOL)createFileAtDocumentsWithName:(NSString *)aFilename
106                               content:(NSData *)aContent
107 {
108     NSString *filePath =[self getFullDocumentPathWithName:aFilename];
109     BOOL result = [self createFileWithPath:filePath
110                                    content:aContent];
111     return result;
112 }
113 
114 + (NSString *)createFileAtTmpWithName:(NSString *)aFilename
115                               content:(NSData *)aContent
116 {
117     NSString *filePath =[self getFullTmpPathWithName:aFilename];
118     BOOL result = [self createFileWithPath:filePath
119                                    content:aContent];
120     if(!result)
121     {
122         filePath = nil;
123     }
124     return filePath;
125     
126 }
127 
128 + (NSString *)createFileWithName:(NSString *)aFilename
129                          content:(NSData *)aContent
130 {
131     NSString *filePath =[self getFullDocumentPathWithName:aFilename];
132     BOOL result = [self createFileWithPath:filePath
133                                    content:aContent];
134     if(!result)
135     {
136         filePath = nil;
137     }
138     return filePath;
139 }
140 
141 #pragma mark Caches下创建文件
142 + (BOOL)createFileAtCachesWithName:(NSString *)aFilename
143                            content:(NSData *)aContent
144 {
145     NSString *filePath =[self getFullCachesPathWithName:aFilename];
146     BOOL result = [self createFileWithPath:filePath
147                                    content:aContent];
148     return result;
149 }
150 #pragma mark 根据文件名称获取Caches的文件名的全路径,需要自己释放
151 + (NSString *)getFullCachesPathWithName:(NSString *)aFileName
152 {
153     return [[self getCachesPath] stringByAppendingPathComponent:aFileName];
154 }
155 
156 
157 + (NSString *)addSubPath:(NSString *)aSubPath
158                   toPath:(NSString *)aPath
159 {
160     return [aPath stringByAppendingPathComponent:aSubPath];
161 }
162 
163 #pragma mark 根据文件名称获取documents的文件名的全路径,需要自己释放
164 + (NSString *)getFullDocumentPathWithName:(NSString *)aFileName
165 {
166     return [[self getDocumentPath] stringByAppendingPathComponent:aFileName];
167 }
168 
169 #pragma mark 根据文件名称获取tmp的文件名的全路径,需要自己释放
170 + (NSString *)getFullTmpPathWithName:(NSString *)aFileName
171 {
172     return [[self getTmpPath] stringByAppendingPathComponent:aFileName];
173 }
174 
175 
176 #pragma mark 获取documents的全路径
177 + (NSString *)getDocumentPath
178 {
179     NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
180     NSString *result = [pathArray objectAtIndex:0];
181     return result;
182     
183 }
184 
185 + (NSString *)getHomePath
186 {
187     NSString *home = [@"~" stringByExpandingTildeInPath];
188     return home;
189 }
190 
191 #pragma mark 删除文件
192 + (BOOL)deleteFileWithName:(NSString *)aFileName
193                      error:(NSError **)aError
194 {
195     NSFileManager *tempFileManager = [self getNSFileManager];
196     return [tempFileManager removeItemAtPath:aFileName
197                                        error:aError];
198 }
199 
200 
201 + (BOOL)deleteFileWithUrl:(NSURL *)aUrl error:(NSError **)aError
202 {
203     return [[self getNSFileManager] removeItemAtURL:aUrl error:aError];
204 }
205 
206 #pragma mark 删除文件夹下的所有文件
207 + (BOOL)deleteAllFileAtPath:(NSString *)aPath
208 {
209     BOOL result = NO;
210     NSArray *fileArray = [self getContentsOfDirectoryAtPath:aPath];
211     
212     
213     NSString *filePath = nil;
214     
215     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
216     for (int i = 0; i<[fileArray count]; i++)
217     {
218         filePath = [aPath stringByAppendingPathComponent:[fileArray objectAtIndex:i]];
219         result = [[self getNSFileManager] removeItemAtPath:filePath
220                                                      error:nil];
221         if (!result)
222         {
223             break;
224         }
225         filePath = nil;
226     }
227     [pool drain];
228     return result;
229 }
230 
231 #pragma mark 根据文件名删除document下的文件
232 + (BOOL)deleteFileAtDocumentsWithName:(NSString *)aFilename
233                                 error:(NSError **)aError
234 {
235     NSString *filePath = [self getFullDocumentPathWithName:aFilename];
236     return [self deleteFileWithName:filePath
237                               error:aError];
238 }
239 
240 #pragma mark 获取tmp路径
241 + (NSString *)getTmpPath
242 {
243     NSString *pathName = [NSHomeDirectory() stringByAppendingPathComponent:@"tmp"];
244     return pathName;
245 }
246 
247 #pragma mark 获取caches路径
248 + (NSString *)getCachesPath
249 {
250     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
251     return [paths objectAtIndex:0];
252 }
253 
254 #pragma mark 在Document下创建文件目录
255 + (BOOL)createDirectoryAtDocument:(NSString *)aDirectory
256 {
257     NSFileManager *tempFileManager = [self getNSFileManager];
258     NSString * directoryAll = [self getFullDocumentPathWithName:aDirectory];
259     
260     BOOL result = [tempFileManager createDirectoryAtPath:directoryAll
261                              withIntermediateDirectories:YES
262                                               attributes:nil
263                                                    error:nil];
264     return result;
265 }
266 
267 #pragma mark 读取文件
268 + (NSData *)readFileWithPath:(NSString *)aPath
269 {
270     NSData *data = [NSData dataWithContentsOfFile:aPath];
271     return data;
272 }
273 
274 + (NSData *)readFileWithURL:(NSURL *)aUrl
275 {
276     NSData *data = [NSData dataWithContentsOfURL:aUrl];
277     return data;
278 }
279 + (NSData *)readFileAtDocumentsWithFileName:(NSString *)aFileName
280 {
281     NSString *fullPathWithName =  [self getFullDocumentPathWithName:aFileName];
282     WALog(fullPathWithName);
283     NSData *data = [NSData dataWithContentsOfFile:fullPathWithName];
284     return data;
285 }
286 
287 #pragma mark 遍历文件夹下的所有文件,不含子文件
288 + (NSArray *)getContentsOfDirectoryAtPath:(NSString *)aDirString
289 
290 {
291     NSFileManager *tempFileManager = [self getNSFileManager];
292     return [tempFileManager contentsOfDirectoryAtPath:aDirString
293                                                 error:nil];
294 }
295 
296 
297 + (NSArray *)getContentsOfDirectoryByTimeOrderAtPath:(NSString *)aDireString
298 {
299     NSArray *files = [CWAFileUtil getAllFilesAtPath:(NSString *)aDireString];
300     
301     NSMutableArray *iUrls = [[NSMutableArray alloc] initWithCapacity:1];
302     NSArray *sortedFiles = nil;
303     
304     if([files count] > 0)
305     {
306         sortedFiles = [files sortedArrayUsingComparator:^(NSString *url1, NSString *url2)
307                        {
308                            
309                            NSDictionary *fileAttributes1 = [[CWAFileUtil getNSFileManager] attributesOfItemAtPath:url1
310                                                                                                             error:nil];
311                            
312                            NSDictionary *fileAttributes2 = [[CWAFileUtil getNSFileManager] attributesOfItemAtPath:url2
313                                                                                                             error:nil];
314                            NSDate *date1 = [fileAttributes1 objectForKey:NSFileCreationDate] ;
315                            
316                            NSDate *date2 = [fileAttributes2 objectForKey:NSFileCreationDate] ;
317                            return [date2 compare:date1];
318                        }];
319     }
320     
321     for (int i = 0; i < [sortedFiles count]; i++)
322     {
323         NSURL *url = [NSURL fileURLWithPath:[sortedFiles objectAtIndex:i]];
324         [iUrls addObject:url];
325     }
326     
327     return [iUrls autorelease];
328     
329 }
330 
331 + (NSArray *)getContentsOfTmpDirectorByTimeOrder
332 {
333     return [self getContentsOfDirectoryByTimeOrderAtPath:[self getTmpPath]];
334 }
335 
336 + (unsigned long long)fileSizeAtPaht:(NSString *)aPath
337 {
338     return  [[[self getNSFileManager] attributesOfItemAtPath:aPath  error:nil] fileSize];
339 }
340 
341 
342 #pragma mark 遍历文件夹下的所有文件,含子文件
343 + (NSArray *)getAllFilesAtPath:(NSString *)aDirString
344 {
345     NSMutableArray *temPathArray = [NSMutableArray array];
346     
347     NSFileManager *tempFileManager =  [self getNSFileManager];
348     NSArray *tempArray = [self getContentsOfDirectoryAtPath:aDirString];
349     NSString *fullPath = nil;
350     
351     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
352     for (NSString *fileName in tempArray)
353     {
354         
355         BOOL flag = YES;
356         fullPath = [aDirString stringByAppendingPathComponent:fileName];
357         
358         //判断是否存在
359         if ([tempFileManager fileExistsAtPath:fullPath
360                                   isDirectory:&flag])
361         {
362             //不是目录,直接添加
363             if (!flag)
364             {
365                 // ignore .DS_Store
366                 if (![[fileName substringToIndex:1] isEqualToString:@"."])
367                 {
368                     [temPathArray addObject:fullPath];
369                 }
370             }
371             //如果是目录的话,以当前文件夹为key,文件夹下的子文件名为value,递归调用
372             else
373             {
374                 NSArray *subPathArray = [self getAllFilesAtPath:fullPath];
375                 //        NSDictionary *subPathDic = [[NSDictionary alloc] initWithObjectsAndKeys:subPathArray,fullPath,nil];
376                 [temPathArray addObjectsFromArray:subPathArray];
377                 //        [subPathDic release];
378             }
379         }
380         fullPath = nil;
381         
382     }
383     [pool drain];
384     NSArray *resultArray = [NSArray arrayWithArray:temPathArray];
385     
386     
387     return resultArray;
388     
389 }
390 
391 #pragma mark 复制一个目录下的文件到另外一个目录,前后两个必须一致,要么都是目录,要么都是文件
392 + (BOOL) copyItemAtPath:(NSString *)aPath
393                  toPath:(NSString *)aDestinationPath
394                   error:(NSError **)aError
395 {
396     NSFileManager *tempFileManager = [self getNSFileManager];
397     return [tempFileManager copyItemAtPath:aPath
398                                     toPath:aDestinationPath 
399                                      error:aError];
400 }
401 
402 #pragma mark 重命名文件
403 + (BOOL)renameFileNameFrom:(NSString *)aOldName 
404                     toPath:(NSString *)aNewName 
405                      error:(NSError **)aError{
406     NSFileManager *tempFileManager = [self getNSFileManager];
407     BOOL result =  [tempFileManager moveItemAtPath:aOldName 
408                                             toPath:aNewName 
409                                              error:aError];
410     return result;
411 }
原文地址:https://www.cnblogs.com/eagle927183/p/3501885.html