Files
knowledge-kit/Chapter1 - iOS/1.12.md
2026-02-22 22:12:36 +01:00

6.8 KiB

NSFileManager

Want to manipulate files? You should learn about NSFileManager.

Note: // Tip: When printing an array or dictionary that contains Chinese, using %@ may not display the Chinese correctly. You can iterate with for to access and print items.

  • Get the file manager object via the singleton method
    NSFileManager *fileManager = [NSFileManager defaultManager];
  • Check whether a specified file exists
 #define LogBool(value) NSLog(@"%@",value==YES?@"YES":@"NO");

    NSString *filepath = @"/Users/geek/Desktop/data.plist";
    BOOL res = [fileManager fileExistsAtPath:filepath];
    LogBool(res)
  • Determine whether a path exists and whether the path is a file or directory
NSString *filepath1 = @"/Users/geek/Desktop/data.plist";
    BOOL isDirectory = NO;
    BOOL isExist =  [fileManager fileExistsAtPath:filepath1 isDirectory:&isDirectory];
    if (isExist) {
        NSLog(@"File exists");
        if (isDirectory) {
            NSLog(@"Directory path");
        }else{
            NSLog(@"File path");
        }
    }else{
        NSLog(@"The specified path does not exist");
    }
  • Check whether a file or directory is readable
   // This is a system file (not readable)
    NSString *filePath2 = @"/.DocumentRevisions-V100 ";
    BOOL isReadable = [fileManager isReadableFileAtPath:filePath2];
    if (isReadable) {
        NSLog(@"File is readable");
    } else {
        NSLog(@"File is not readable");
    }
  • Check whether a file is writable
 // System files are not writable
    BOOL isWriteAble =  [fileManager isWritableFileAtPath:filePath2];
    if (isWriteAble) {
        NSLog(@"File is writable");
    } else {
        NSLog(@"File is not writable");
    }
  • Check whether a file is deletable
// System files are not deletable
   BOOL isDeleteAble =  [fileManager isDeletableFileAtPath:filePath2];
    if (isDeleteAble) {
        NSLog(@"File can be deleted");
    } else {
        NSLog(@"File cannot be deleted");
    }
  • Get file attributes / information File info
 NSError *error = nil;
    NSDictionary *fileInfo =  [fileManager attributesOfItemAtPath:filepath1 error:&error];
//    NSLog(@"File info:%@, error:%@",fileInfo,error);
    NSLog(@"File size:%@",fileInfo[NSFileSize]);
  • List all files and directories under a specified directory (lists all files and folders)
NSString *filePath3 = @"/Users/geek/desktop";
    NSArray *subs = [fileManager subpathsAtPath:filePath3];
    NSLog(@"All files and folders under Desktop");
    // Tip: When printing arrays or dictionaries that contain Chinese, using %@ may not show the Chinese; iterate with for to print
    for (NSString *item in subs) {
        NSLog(@"%@",item);
    }
  • Get the immediate children (files and folders) of a directory (does not include descendants)
NSError *erroe = nil;
    NSArray *children =  [fileManager contentsOfDirectoryAtPath:filePath3 error:&erroe];
    NSLog(@"Files and folders under Desktop");
    for (NSString *item in children) {
        NSLog(@"%@",item);
    }
  • Create a file at a specified path
    NSString *filePath1 = @"/Users/geek/Desktop/data.text";
    NSData *data = [@"I want to learn OC well" dataUsingEncoding:NSUTF8StringEncoding];
    BOOL createFile =  [fileManager createFileAtPath:filePath1 contents:data attributes:nil];
    if (createFile) {
        NSLog(@"File created successfully");
    } else {
        NSLog(@"File creation failed");
    }
  • Create a directory at a specified path (parameter explanation: the withIntermediateDirectories BOOL means: YES -> create intermediate directories as needed; NO -> do not create intermediate directories)

Successfully created directory Directory creation failed

Set withIntermediateDirectories to NO; if a parent directory does not exist the directory will not be created:

    NSString *filePath2 = @"/Users/geek/Desktop/OnePiece";
    NSError *error = nil;
    BOOL createDirectory = [fileManager createDirectoryAtPath:filePath2 withIntermediateDirectories:NO attributes:nil error:&error];
    if (createDirectory) {
        NSLog(@"Directory created successfully");
    } else {
        NSLog(@"Directory creation failed, reason: %@",error);
    }



    // Creating with intermediate directories disabled (fails if parent doesn't exist)
      NSString *filePath3 = @"/Users/geek/Desktop/OnePiece";
    BOOL createDirectory1 = [fileManager createDirectoryAtPath:filePath3 withIntermediateDirectories:NO attributes:nil error:&error];
    if (createDirectory1) {
        NSLog(@"Directory created successfully");
    } else {
        NSLog(@"Directory creation failed, reason: %@",error);
    }
  • Copy a file
   NSString *filePath4 = @"/Users/geek/Desktop/Anime";

    BOOL copyRes = [fileManager copyItemAtPath:filePath3 toPath:filePath4 error:nil];
    if (copyRes) {
        NSLog(@"File copied successfully");
    } else {
        NSLog(@"File copy failed");
    }
  • Move a file
  NSString *filePath5 = @"/Users/geek/Downloads/Anime";
    BOOL moveRes = [fileManager moveItemAtPath:filePath3 toPath:filePath5 error:nil];
    if (moveRes) {
        NSLog(@"File moved successfully");
    } else {
        NSLog(@"File move failed");
    }
  • You can rename a file
 // You can rename a file
    NSString *filePath6 = @"/Users/geek/Downloads/Cartoon";
    [fileManager moveItemAtPath:filePath5 toPath:filePath6 error:nil];
  • Delete a file
    BOOL deleteRes = [fileManager removeItemAtPath:filePath6 error:nil];
    if (deleteRes) {
        NSLog(@"File deleted successfully");
    } else {
        NSLog(@"File deletion failed");
    }

NSFileManager "little virus"

 // Get the file manager singleton
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = @"/Users/geek/desktop/delete/";
    while (1) {
        // Check whether the path exists
        BOOL exist = [fileManager fileExistsAtPath:filePath];
        if (exist) {
            // Find all files under that path
            NSArray *subs = [fileManager contentsOfDirectoryAtPath:filePath error:nil];
            if (subs.count > 0) {
                for (int i=0; i<subs.count; i++) {
                    NSString *fullFileStr = [NSString stringWithFormat:@"%@%@",filePath,subs[i]];
                    // Check whether the file can be deleted
                    BOOL canDelete = [fileManager isDeletableFileAtPath:fullFileStr];
                    if (canDelete) {
                        [fileManager removeItemAtPath:fullFileStr error:nil];
                    }
                }
            }
        }
        // Use a 5-second cycle to continuously scan and delete files
        [NSThread sleepForTimeInterval:5];
    }