天天看点

NSFileHandler和沙盒模式

沙盒模式下的文件路径:

-(void)getSystemFilePath{
    
    //沙盒所在的根目录
    NSString *homeDirectory = NSHomeDirectory();
    NSLog(@"path:%@", homeDirectory);
    
    //应用程序路径
    NSString*appPath = [[NSBundle mainBundle] resourcePath];
    NSLog(@"path:%@", appPath);
    
    //document目录
    NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPaths = [docPaths objectAtIndex:0];
    NSLog(@"path:%@", documentPaths);
    
    //Cache目录
    NSArray *cacPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [cacPaths objectAtIndex:0];
    NSLog(@"%@", cachePath);
    
    //获取Library目录
    NSArray *libPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *libraryPath = [libPaths objectAtIndex:0];
    NSLog(@"%@", libraryPath);
    
    //获取Tmp目录
    NSString *tmpDir = NSTemporaryDirectory();
    NSLog(@"%@", tmpDir);
    
    
    
}
           

运行结果:

homeDirectory:/Users/baihe

appPath:/Users/baihe/Library/Developer/Xcode/DerivedData/FileManage-bsjiooyzykamvnfrvtvuuejgiufb/Build/Products/Debug

documentPaths:/Users/baihe/Documents

cachePath:/Users/baihe/Library/Caches

libraryPath:/Users/baihe/Library

tmpDir:/var/folders/gg/cc6n2tms01j48j3l9g6sph100000gp/T/
           

文件的读取:

#pragma mark NSFileHandler和NSFileManager读取文件

-(void)readToFile{
    
    
    NSFileManager *fm=[NSFileManager defaultManager];
    
    //读取沙盒文件
   NSArray *sorecePath= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
   NSString *filePath= [sorecePath objectAtIndex:0];
    
    filePath=[filePath stringByAppendingPathComponent:@"text_list22.txt"];
    
    NSLog(@"文件路径%@",filePath);

    if ([fm fileExistsAtPath:filePath ]) {
        NSLog(@"读取文件存在");
        
        NSFileHandle *inFile=[NSFileHandle fileHandleForReadingAtPath:filePath];
        
        //偏移量
        
//        NSUInteger len=[[inFile availableData]length];
//        
//        [inFile seekToFileOffset:len/2];
        
        NSData *readData=[inFile readDataToEndOfFile];
        
        NSLog(@"readData=%@",[[NSString alloc]initWithData:readData encoding:NSUTF8StringEncoding]);
        
        [inFile closeFile];
        
        [self getSystemFilePath];
        
    }else{
    
        NSLog(@"读取文件不存在");
    }
    
}
           

write文件

-(void)writeToFile{
    
    
    NSFileManager* fm=[NSFileManager defaultManager];//文件进行的操作以及文件信息的获取
    
    //查找文件
    NSArray *directoryPaths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    //查询文件 0表示document下的文件
    NSString *documentDirectory =[directoryPaths objectAtIndex:0];
    
    //查找的文件名
    NSString* fileName =[documentDirectory stringByAppendingPathComponent:@"text_list22.txt"];
    
    NSLog(@"文件路径:%@",fileName);
    
    if (![fm fileExistsAtPath:fileName]) {
        
        NSLog(@"文件路径不存在:%@",fileName);
        
    }else{
        
        BOOL b=[fm createFileAtPath:fileName contents:nil attributes:nil];
        if (b) {
            NSLog(@"文件创建成功");
        }else{
            NSLog(@"文件创建失败");
        }
        
    }
    
     NSFileHandle *outfile=[NSFileHandle fileHandleForWritingAtPath:fileName];//主要是对文件内容进行读取和写入操作
     NSString *[email protected]"object-c";
    [ outfile truncateFileAtOffset:0]; //将输出文件的长度设为0
    
//    NSFileHandle *outfile=[NSFileHandle fileHandleForUpdatingAtPath:fileName];
//    [outfile seekToEndOfFile];//将节点跳到文件的末尾
//    NSString *[email protected]"中文";

    [outfile writeData:[buffer dataUsingEncoding:NSUTF8StringEncoding]];  //写入输入
    
    [outfile closeFile];
    
}
           

NSFileHandler常用方法:

+ (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;  关闭文件
           

NSFileManage常用方法

-(NSData *)contentsAtPath:path	从path所代表的文件中读取数据
-(BOOL)createFileAtPath:path contents:(BOOL)data attributes:attr	将数据写入文件
-(BOOL)removeFileAtPath:path handler:handler	将path所代表的文件删除
-(BOOL)movePath:from toPath:to handler:handler	移动或者重命名文件,to所代表的文件不能是已经存在的文件
-(BOOL)copyPath:from toPath:to handler:handler	复制文件,to所代表的文件不能是已经存在的文件
-(BOOL)contentsEqualAtPath:path1 andPath:path2	比较path1和path2所代表的文件
-(BOOL)fileExistsAtPath:path	检查path所代表的文件是否存在
-(BOOL)isReadableFileAtPath:path	检查path所代表的文件是否存在、是否可读
-(BOOL)isWritableFileAtPath:path	检查path所代表的文件是否存在、是否可写
-(NSDictionary *)fileAttributesAtPath:path traverseLink:(BOOL)flag	获取path所代表的文件属性
-(BOOL)changeFileAttributes:attr atPath:path	改变文件属性
           

//使用方法如下:

NSFileManager *fm=[NSFileManager defaultManager];
        //读取沙盒文件
        NSArray *sorecePath= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        NSString *filePath= [sorecePath objectAtIndex:0];
        
        filePath=[filePath stringByAppendingPathComponent:@"text_list22"];
        
        [fm removeItemAtPath:filePath error:nil];//移除文件.
        [fm createDirectoryAtPath:filePath withIntermediateDirectories:YES
                       attributes:nil error:nil];//创建文件夹
        [fm createFileAtPath:[filePath stringByAppendingPathComponent:@"text_list22.txt"] contents:nil attributes:nil];//创建文件