UIFileManager

// 获取DocumentsPath的路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSLog(@"path : %@", path);

// 创建文件夹
NSString *documentsPath = path;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *iosDirectory = [documentsPath stringByAppendingString:@"iOS"];
BOOL isSuccess = [fileManager createDirectoryAtPath:iosDirectory withIntermediateDirectories:YES attributes:nil error:nil];
if (isSuccess) {
    NSLog(@"success");
}else{
    NSLog(@"fail");
}



// 创建文件   在这个路径: DocumentsiOS下创建iOS.txt 文件.
NSString *iOSPath = [iosDirectory stringByAppendingPathComponent:@"iOS.txt"];

BOOL isSucceed = [fileManager createFileAtPath:iOSPath contents:nil attributes:nil];
if (isSucceed) {
    NSLog(@"文件创建成功");
}else{
    NSLog(@"哦哦, 失败了");
}



//  写文件
NSString *content = @"我要写数据啦";
BOOL writeSuccess = [content writeToFile:iOSPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
if (writeSuccess) {
    NSLog(@"write success");
}else{
    NSLog(@"write fail");
}

// 读取文件内容
content = [NSString stringWithContentsOfFile:iOSPath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"read success: %@", content);


// 判断文件是否存在
BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:iOSPath];
if (isExist) {
    NSLog(@"存在");
}else{
    NSLog(@"不存在");
}


// 计算文件大小
if (isExist) {
    unsigned long long fileSize = [[fileManager attributesOfItemAtPath:iOSPath error:nil] fileSize];
    NSLog(@"%lld", fileSize);
}else{
    NSLog(@"该文件不存在");
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容