存取文件

    //获取Documents目录

    NSString *home=NSHomeDirectory();

    NSLog(@"%@",home);

    NSString *documents=[home stringByAppendingPathComponent:@"Documents/text.txt"];

    NSLog(@"%@",documents);

    

    

    //获取主包目录

    NSString *path=[[NSBundle mainBundle]bundlePath];

    NSLog(@"%@",path);

    

    NSLog(@"-----------");

    NSString *tmp=NSTemporaryDirectory();

    NSLog(@"%@",tmp);

    NSLog(@"++++++++++");

    

    

    //查找某类型文件的路径

    NSArray *array=NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);

    NSLog(@"%@",array);

    NSString *str=array[0];

    NSLog(@"%@",str);

    

    

    

    

    

    NSLog(@"---create---");

    

    //创建文件

    NSFileManager *file=[NSFileManager defaultManager];

    if ([file createFileAtPath:documents contents:[documents dataUsingEncoding:NSUTF8StringEncoding] attributes:nil]) {

        NSLog(@"--yse");

    }

    

    

    //删除文件

//    if ([file removeItemAtPath:documents error:nil]) {

//        NSLog(@"yse");

//    }

    

    

    

    //创建文件夹

//    if ([file createDirectoryAtPath:documents withIntermediateDirectories:YES attributes:nil error:nil]) {

//        NSLog(@"++yes");

//    }

    

//    NSString *str1= [[NSString alloc]initWithData:[file contentsAtPath:documents] encoding:NSUTF8StringEncoding];

//    NSLog(@"---%@",str1);

//    

    

    //以只写方式打开文件

    NSFileHandle *write=[NSFileHandle fileHandleForWritingAtPath:documents];

    

    

    //跳到文件末尾

    [write seekToEndOfFile];

    

    //写入文件

    [write writeData:[documents dataUsingEncoding:NSUTF8StringEncoding]];

    NSLog(@"%llu",write.offsetInFile);

    

    //关闭文件

    [write closeFile];

    

    

    //以只读方式打开文件

    NSFileHandle *read=[NSFileHandle fileHandleForReadingAtPath:documents];

    

    

    //读取文件内容

    NSString *s=[[NSString alloc]initWithData:[read readDataToEndOfFile] encoding:NSUTF8StringEncoding];

    NSLog(@"%@",s);

    

    //关闭文件

    [read closeFile];

    

    

    //以可读可写的方式打开文件

    NSFileHandle *update=[NSFileHandle fileHandleForUpdatingAtPath:documents];

    

    //跳到指定位置

    [update seekToFileOffset:178];

    

    //读取文件

    NSString *s1=[[NSString alloc]initWithData:[update readDataToEndOfFile] encoding:NSUTF8StringEncoding];

    NSLog(@"%@",s1);

    

    //写入文件

    [update writeData:[documents dataUsingEncoding:NSUTF8StringEncoding]];

    

    //跳到文件开始

    [update seekToFileOffset:0];

    

    //从文件读取100个字节

    NSString *s2=[[NSString alloc]initWithData:[update readDataOfLength:100] encoding:NSUTF8StringEncoding];

    NSLog(@"%@",s2);

    

    //打印当前读写指针位置

    NSLog(@"%llu",update.offsetInFile);

    

    //关闭文件

    [update closeFile];

posted on 2014-10-18 21:57  陈丰波  阅读(175)  评论(0编辑  收藏  举报