NSfileManager 之我的见解

首先你要找到沙盒的路径 然后创建文件夹 之后创建文件 然后写入文件  读取文件 基本就这些了

废话不多说下面上代码

1.获取沙盒的路径

- (NSString*)getDocumentsPath{
    //获取Documents路径
 
    NSArray *paths  = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSLog(@"path:%@",path);
    return path;
}

2.创建文件夹

//创建文件夹
- (void)createDirectory{
    NSString *documentsPath = [self getDocumentsPath];
    NSFileManager *fileMamager = [NSFileManager defaultManager];
    NSString *iOSDirectory  =[documentsPath stringByAppendingPathComponent:@"iOS"];
    BOOL isSuccess  =[fileMamager createDirectoryAtPath:iOSDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    if (isSuccess) {
        NSLog(@"isSuccess");
    }else {
        NSLog(@"fail");
    }
}

3.创建文件

//创建文件
- (void)createFile{
    NSString *documentsPath = [self getDocumentsPath];
    NSFileManager *fileMamager = [NSFileManager defaultManager];
    NSString *iOSPath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
    BOOL isSuccess  =[fileMamager createFileAtPath:iOSPath contents:nil attributes:nil];
    if (isSuccess) {
        NSLog(@"isSuccess");
    }else {
        NSLog(@"fail");
    }

    
}

4.写入文件

/写文件
- (void)writeFile{
    NSString *documentsPath = [self  getDocumentsPath];
    NSString *iOSPath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
    NSString *content =@"我要写数据啦";
    BOOL isSuccess  =[content writeToFile:iOSPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    if (isSuccess) {
        NSLog(@"isSuccess");
    }else {
        NSLog(@"fail");
    }
    
}

5.读取文件内容

//读取文件的内容
- (void)readFileContent{
    NSString *documentsPath = [self  getDocumentsPath];
    NSString *iOSPath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
    NSString *content = [NSString stringWithContentsOfFile:iOSPath encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"read success:%@",content);
}

6.获取文件的大小

//获取文件的大小
- (unsigned long long)fileSizeAtApth :(NSString *)filePath{
    NSFileManager *fileMamager =[NSFileManager defaultManager];
    BOOL isExist  =[fileMamager fileExistsAtPath:filePath];
    if (isExist) {
        unsigned long long fileSize =[[fileMamager attributesOfItemAtPath:filePath error:nil]fileSize];
        return fileSize;
    }else {
        NSLog(@"file is not exist");
        return 0;
    }
}

额。。。现就这些吧啊




你可能感兴趣的:(manager,沙盒,NSFile)