Categories
objective-c

objective-c 文件系统

objective-c 文件系统依赖NSFileManager

objective-c file对象 为NSFileHandle

NSFileManager 返回的文件路径对象都是NSString

fileManager.currentDirectoryPath; //返回当前进程目录

BOOL isSuccess = [fileManager createFileAtPath:path contents:nil attributes:nil]; // 创建文件

 BOOL isDirectorySuccess = [fileManager createDirectoryAtPath:directory withIntermediateDirectories:true attributes:nil error:nil]; //创建文件夹

BOOL isRemoveSuccess = [fileManager removeItemAtPath:path error:nil];//删除文件或者文件夹

以下是读写文件文件 和文件对象操作

NSString 对应字符串

NSData 对应byte数组

NSFileHandle 对应文件对象

 NSString *homePath  = NSHomeDirectory( );
 NSString *sourcePath = [homePath stringByAppendingPathConmpone:@"testfile.text"];   
             
 NSFileHandle *fielHandle = [NSFileHandle fileHandleForUpdatingAtPath:sourcePath];   //创建文件对象
                    
 [fileHandle seekToEndOfFile];  将节点跳到文件的末尾  
        
 NSString *str = @"追加的数据"   
                
 NSData* stringData  = [str  dataUsingEncoding:NSUTF8StringEncoding];  
        
 [fileHandle writeData:stringData]; //追加写入NSData数据       
 [fileHandle closeFile]; //关闭文件对象

通过fileManager 在创建文件时写入NSData

NSString *content = @"content2";
NSData *data = [content dataUsingEncoding:NSUTF8StringEncoding];
        BOOL isSuccess = [fileManager createFileAtPath:path contents:data attributes:nil];
        if (isSuccess) {
            NSLog(@"file created");
        }else{
            NSLog(@"file not created");
        }

通过NSMutableString 写入文件

   NSMutableString *content = [NSMutableString new];
        [content appendString:@"helloworld"];
        NSString *homePath = NSHomeDirectory();
        NSString *path = [homePath stringByAppendingPathComponent: @"myfile.txt"];

        BOOL isWriteSuccess = [content writeToFile:path atomically:true encoding:NSUTF8StringEncoding error:nil];
        if (isWriteSuccess) {
            NSLog(@"content writed");
        }else{
            NSLog(@"content not writed");
        }

通过NSData 写入文件


        NSString *content = @"helloworldNSdata2";
        NSString *homePath = NSHomeDirectory();
        NSString *path = [homePath stringByAppendingPathComponent: @"myfile.txt"];

        NSData *data = [content dataUsingEncoding:NSUTF8StringEncoding];
        
        BOOL isWriteSuccess = [data writeToFile:path atomically:true];
        if (isWriteSuccess) {
            NSLog(@"content writed");
        }else{
            NSLog(@"content not writed");
        }
      

以下是流操作 NSInputStream和NSOutputStream

用文件流说明流章节比较复杂 下个章节单独说明

Leave a Reply