本文主要是介绍NSFileManager和NSFileHandle文件操作,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一.NSFileManager文件外操作
1.文件和目录的创建
(1).步骤
//1.创建一个单例类的对象
NSFileManager *fileManage = [NSFileManager defaultManager];//2.创建普通文件,如果两个文件的文件名相同,会用新文件覆盖旧文件
- (BOOL)createFileAtPath:(NSString *)path contents:(NSData *)data attributes:(NSDictionary *)attr;//3. 创建文件夹/目录
- (BOOL)createDirectoryAtPath:(NSString *)path withIntermediateDirectories:(BOOL)createIntermediates attributes:(NSDictionary *)attributes error:(NSError **)error NS_AVAILABLE(10_5, 2_0);
(2)程序举例
NSString *pathDesktop = @"/Users/Story5/Desktop";//桌面路径
NSString *string = @"fileContent";
NSData *dataFromString = [string dataUsingEncoding:NSUTF8StringEncoding];NSFileManager *fileManage = [NSFileManager defaultManager];//创建一个单例类的对象[fileManage createFileAtPath:[pathDesktop stringByAppendingString:@"/file.txt"] contents:dataFromString attributes:nil];NSError *error = nil;
[fileManage createDirectoryAtPath:[pathDesktop stringByAppendingString:@"/dir/dir1"] withIntermediateDirectories:YES attributes:nil error:&error];if (error != nil) {//函数调用失败NSLog(@"createDirectoryAtPath error: %@", [error localizedFailureReason]);}
2.文件和目录的复制
- (BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error NS_AVAILABLE(10_5, 2_0);
3.文件和目录的剪切
- (BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error NS_AVAILABLE(10_5, 2_0);
4.文件和目录的删除
- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error NS_AVAILABLE(10_5, 2_0);
5.目录的遍历
(1)浅度遍历
- (nullable NSArray<NSString *> *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error NS_AVAILABLE(10_5, 2_0);
(2)深度遍历
- (nullable NSArray<NSString *> *)subpathsOfDirectoryAtPath:(NSString *)path error:(NSError **)error NS_AVAILABLE(10_5, 2_0);
6.获取文件属性
- (nullable NSDictionary<NSString *, id> *)attributesOfItemAtPath:(NSString *)path error:(NSError **)error NS_AVAILABLE(10_5, 2_0);
二.NSFileHandle文件操作
1.文件的打开
(1)以只读方式打开
+ (nullable instancetype)fileHandleForReadingAtPath:(NSString *)path;
(2)以只写方式打开
+ (nullable instancetype)fileHandleForWritingAtPath:(NSString *)path;
(3)以读写方式打开
+ (nullable instancetype)fileHandleForUpdatingAtPath:(NSString *)path;
2.文件内容的读取
//读
- (NSData *)readDataOfLength:(NSUInteger)length;
- (NSData *)readDataToEndOfFile;//写
- (void)writeData:(NSData *)data;
3.文件偏移量设置
- (unsigned long long)seekToEndOfFile;
- (void)seekToFileOffset:(unsigned long long)offset;
这篇关于NSFileManager和NSFileHandle文件操作的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!