文件操作
2017-07-02 本文已影响2人
u14e
1. 沙盒路径的处理
- 沙盒路径:
NSString *homePath = NSHomeDirectory()
- Documents路径:
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [docPaths firstObject];
- Library路径:
NSArray *libPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *libraryPath = libPaths[0];
- tmp路径:
NSString *tmpPath = NSTemporaryDirectory()
2. NSString类路径处理函数的处理
NSString *path = @"/data/Containers/Data/Application/test.png";
// 获取路径的各个组成部分
NSArray *array = [path pathComponents];
NSLog(@"%@", array);
// 提取路径最后一个组成部分
NSString *name = [path lastPathComponent];
NSLog(@"%@", name);
// 删除路径的最后一个组成部分
NSString *string = [path stringByDeletingLastPathComponent];
NSLog(@"%@", string);
// 追加
NSString *addStr = [string stringByAppendingPathComponent:@"name.txt"];
NSLog(@"%@", addStr);
3. NSData处理
- (void) dataChange: (NSData *) data {
// NSData -> NSString
NSString *dataToString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// NSString -> NSData
NSData *stringToData = [dataToString dataUsingEncoding:NSUTF8StringEncoding];
// NSData -> UIImage
UIImage *image = [UIImage imageWithData:stringToData];
// UIImage -> NSData
NSData *data1 = UIImagePNGRepresentation(image);
}
4. NSFileHandle类对文件内容的读取和写入
先获取测试路径和文件
NSString *docPath = [self getDocumentsPath];
NSString *testPath = [docPath stringByAppendingPathComponent:@"慕课网"];
NSString *filePath = [testPath stringByAppendingPathComponent:@"note.txt"];
- 创建文件夹
NSFileManager *manager = [NSFileManager defaultManager];
BOOL ret = [manager createDirectoryAtPath:testPath
withIntermediateDirectories:YES
attributes:nil
error:nil];
if (ret) {
NSLog(@"文件夹创建成功");
} else {
NSLog(@"失败");
}
- 创建文件
NSFileManager *manager = [NSFileManager defaultManager];
BOOL ret = [manager createFileAtPath:filePath
contents:nil
attributes:nil];
- 写入内容
NSString *content = @"test for note.";
BOOL ret = [content writeToFile:filePath
atomically:YES
encoding:NSUTF8StringEncoding
error:nil];
- 查看文件是否存在
- (BOOL) fileExist: (NSString *) filePath {
NSFileManager *manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:filePath]) {
return YES;
} else {
return NO;
}
}
- 追加内容
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath]; // 打开文件,准备更新
[fileHandle seekToEndOfFile]; // 将节点调到文件末尾
NSString *addContents = @"add to note.";
NSData *stringToData = [addContents dataUsingEncoding:NSUTF8StringEncoding];
[fileHandle writeData:stringToData];
[fileHandle closeFile]; // 关闭文件
- 删除文件
NSFileManager *manager = [NSFileManager defaultManager];
BOOL ret = [self fileExist:filePath];
if (ret) {
BOOL ret2 = [manager removeItemAtPath:filePath error:nil];
if (ret2) {
NSLog(@"删除成功");
} else {
NSLog(@"删除失败");
}
} else {
NSLog(@"路径不存在");
}