iOS 修改文件名称

2021-04-19  本文已影响0人  KevinChein
- (void)renamedFiles {
  // 找到文件路径
  NSString *filePath = @"/Users/admin/Desktop/指定文件夹";
  // 工程目录
  NSString *BASE_PATH = filePath;
  NSFileManager *myFileManager = [NSFileManager defaultManager];
  NSDirectoryEnumerator *myDirectoryEnumerator = [myFileManager enumeratorAtPath:BASE_PATH];
        
  BOOL isDir = NO;
  BOOL isExist = NO;
        
  //列举目录内容,可以遍历子目录
  for (NSString *path in myDirectoryEnumerator.allObjects) {
      [self.dataLock lock];
      isExist = [myFileManager fileExistsAtPath:[NSString   stringWithFormat:@"%@/%@", BASE_PATH, path] isDirectory:&isDir];
      if (isDir) {
          NSLog(@"目录路径:%@", path);    // 目录路径
      } else {
          NSLog(@"文件路径:%@", path);    // 文件路径
          NSString *containString = @"指定字符串";
         NSString *copyPath = [path mutableCopy];
        
          if ([copyPath containsString:containString]) {
            
              // 原来的文件目录
              NSString* fromFileName = [filePath stringByAppendingPathComponent:path];
            // 改变之后的文件名
              NSString* changedStr = [path stringByReplacingOccurrencesOfString:containString withString:@""];
              // 改变之后的文件目录
              NSString* toFileName = [filePath stringByAppendingPathComponent:changedStr];
            
              NSError *error;
            
              // 替换,其实也是重命名
              BOOL isSuccess = [myFileManager moveItemAtPath:fromFileName toPath:toFileName error:&error];
            
              if (isSuccess) {
                  NSLog(@"rename success");
                
                  BOOL isDelSuccess = [myFileManager removeItemAtPath:path error:nil];
                  if (isDelSuccess) {
                      NSLog(@"remove success");
                  } else {
                      NSLog(@"remove fail");
                  }
              }else{
                  NSLog(@"rename fail");
              }
          }
      }
      [self.dataLock unlock];
  }
}   


- (NSLock *)dataLock{
  if (_dataLock == nil) {
      _dataLock = [[NSLock alloc] init];
  }
  return _dataLock;
}
上一篇下一篇

猜你喜欢

热点阅读