// 获取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(@"该文件不存在");
}