iOS文件管理

2020-03-09  本文已影响0人  Arthur澪

NSFileManager和NSFilehandle类

NSFileManager

NSFileManager类是Foundation框架中用来管理和操作文件、目录等文件系统相关联内容的类。
NSFileHandle类,需要配合NSFileManager文件管理类,对文件内容进行写入、读取数据等操作。实现文件的增删改查等功能

// 获取沙盒路径
 NSString *documentsPath =[self getDocumentPath];

 NSFileManager *fileManager = [NSFileManager defaultManager];
// 拼接, 创建文件夹路径
 NSString * testDirectory = [documentsPath stringByAppendingPathComponent:@"日记"];
 // 创建文件夹
BOOL res = [fileManager createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    
if (res) {
    NSLog(@"文件夹创建成功");
}
    NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];
    BOOL res1 = [fileManager createFileAtPath:testPath contents:nil attributes:nil];
    if (res1) {
        NSLog(@"文件创建成功: %@" ,testPath);
    }

// 写入内容
   NSString * str = @"你是一位好同志";
   BOOL res2 = [str writeToFile:testPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    if (res2) {
        NSLog(@"文件写入成功");
    }
    if ([fileManager fileExistsAtPath:testPath]) {
        NSLog(@" 存在 ");
    }
    BOOL isOK = [fileManager removeItemAtPath:testPath error:nil];
    if (isOK) {
        NSLog(@"-- 成功删除---");
    }
 //目标文件 路径
    NSString *targetPath = [testDirectory stringByAppendingPathComponent:@"test1.txt"];
// 拷贝
    [fileManager copyItemAtPath:testPath toPath:targetPath error:nil]; 
[fileManager moveItemAtPath:testPath toPath:targetPath error:nil];
- (unsigned long long)fileSizeAtPath:(NSString *)filePath {
    NSFileManager *fileManager = [NSFileManager defaultManager];

    BOOL isExist = [fileManager fileExistsAtPath:filePath];

    if (isExist) {
        unsigned long long fileSize = [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];
        return fileSize;
    } else {
        NSLog(@"file is not exist");
        return 0;
    }
}
- (unsigned long long)folderSizeAtPath:(NSString*)folderPath {
    NSFileManager *fileManager = [NSFileManager defaultManager];

    BOOL isExist = [fileManager fileExistsAtPath:folderPath];
    if (isExist) {
        NSEnumerator *childFileEnumerator = [[fileManager subpathsAtPath:folderPath] objectEnumerator];
        unsigned long long folderSize = 0;
        NSString *fileName = @"";

        while ((fileName = [childFileEnumerator nextObject]) != nil){
            NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
            folderSize += [self fileSizeAtPath:fileAbsolutePath];
        }
        return folderSize / (1024.0 * 1024.0);
    } else {
        NSLog(@"file is not exist");
        return 0;
    }
}

NSFilehandle

常用方法

+ (id)fileHandleForReadingAtPath:(NSString *)path //打开一个文件准备读取
+ (id)fileHandleForWritingAtPath:(NSString *)path //打开一个文件准备写入   
+ (id)fileHandleForUpdatingAtPath:(NSString *)path //打开一个文件准备更新
- (NSData *)availableData; //从设备或通道返回可用的数据            
- (NSData *)readDataToEndOfFile; //从当前的节点读取到文件的末尾              
- (NSData *)readDataOfLength:(NSUInteger)length; // 从当前节点开始读取指定的长度数据                           
- (void)writeData:(NSData *)data; //写入数据       
- (unsigned long long)offsetInFile; //获取当前文件的偏移量          
- (void)seekToFileOffset:(unsigned long long)offset; //跳到指定文件的偏移量    
- (unsigned long long)seekToEndOfFile; //跳到文件末尾      
- (void)truncateFileAtOffset:(unsigned long long)offset; //将文件的长度设为offset字节
- (void)closeFile; 关闭文件

    NSFileHandle * handFile = [NSFileHandle fileHandleForUpdatingAtPath:testPath];

   [handFile seekToEndOfFile]; // 文件光标移动末尾
    NSString * str1 = @"追加内容"; // 追加内容
    // 转换文件格式
    NSData * data = [str1 dataUsingEncoding:NSUTF8StringEncoding];
    // 写入
    [handFile writeData:data];
    [handFile closeFile];// 关闭

获取文件

NSString * content = [NSString stringWithContentsOfFile: testPath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"拿到文章的内容  -- %@",content);

文件转换

NSString * string = @"123456";
//NSString 转换为 NSData
NSData * data = [string dataUsingEncoding:NSUTF8StringEncoding];
//NSData 转换为 NSString
NSString * str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    //NSData 转换为 UIImage
    NSString * imagePath = @"/Users...../yyyy.png";
    NSData * imageData = [NSData dataWithContentsOfFile: imagePath];
    UIImage * image = [UIImage imageWithData: imageData];
    //UIImage 转换为 NSData
    NSData * imageData1 = UIImagePNGRepresentation(image);
上一篇 下一篇

猜你喜欢

热点阅读