iOS笔记—文件的写入、读取与操作

有时候,项目中需要将数据持久化存储。我们的做法之一就是将其写入文件。当需要的时候可以从文件中读取出来即可。

//
//  main.m
//  写入文件
//
//  Created by hhg on 15/5/28.
//  Copyright (c) 2015年 hhg. All rights reserved.
//

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        ///  路径 如无则自动创建一个
        NSString *stringPath = @"/Users/hhg/Desktop/string写入文件.txt";
        NSString *dataPath   = @"/Users/hhg/Desktop/data写入文件.txt";
        NSString *arrayPath  = @"/Users/hhg/Desktop/array写入文件.plist";

        // 写入
        NSString *string = @"string写文件";
        BOOL isWriteString =[string writeToFile:stringPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
        if (isWriteString) { NSLog(@"string 文件写入成功"); };

        NSData *data =[[NSData alloc]initWithContentsOfFile:stringPath];
        BOOL isWriteData =[data writeToFile:dataPath atomically:YES];
        if (isWriteData) { NSLog(@"data 文件写入成功"); }

        // 数组在写文件时 包含元素只能是 NSString NSArray NSData NSNumber NSDictionary
        NSString *sanNameStr = @"张三";
        NSString *siNameStr = @"李四";
        NSString *wuNameStr = @"王五";
        NSArray *nameArray = [NSArray arrayWithObjects:sanNameStr, siNameStr, wuNameStr,nil];

        BOOL isWriteArray =[nameArray writeToFile:arrayPath atomically:YES];
        if (isWriteArray) { NSLog(@"array 写入文件成功"); }

        /// 读取文件
        NSString *readStr =[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@" 读取的string为 : %@", readStr);

        NSString *readDataStr =[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@" 读取的data为 :%@", readDataStr);

        NSArray *readArr =[[NSArray alloc]initWithContentsOfFile:arrayPath];
        NSLog(@"读取的array为 :%@",readArr);

        //字典存入plist文件
        NSDictionary *dic =[[NSDictionary alloc]initWithObjectsAndKeys:
                            sanNameStr,@"第一",
                            siNameStr,@"第二",
                            wuNameStr,@"第三",
                            nameArray,@"姓名数组", nil];

        [dic writeToFile:arrayPath atomically:YES];

        NSDictionary *myDic =[[NSDictionary alloc]initWithContentsOfFile:arrayPath];
        NSArray * nameArr =myDic[@"姓名数组"];
        NSLog(@"nameArr : %@",nameArr);
    }
    return 0;
}

当我们正常写完数据之后,后面需要添加新的数据并不能直接像上面那样再次操作。一旦再次操作,会覆盖掉原先的数据。为了避免覆盖,我们需要对添加的数据进行偏移操作。

//
//  main.m
//  添加数据
//
//  Created by hhg on 15/4/29.
//  Copyright (c) 2015年 hhg. All rights reserved.
//

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool
    {
        NSString *path = @"/Users/hhg/Desktop/文件的偏移量.txt";
        NSString*oldStr = @"old string ,";
        [oldStr writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];

        NSFileHandle *wirteFileHandle =[NSFileHandle fileHandleForWritingAtPath:path];

        //添加数据
        NSString *appendString = @"append string";
        NSData *data =[appendString dataUsingEncoding:NSUTF8StringEncoding];

        //设置偏移量   如果不设置偏移量 系统默认从文件一开始添加数据
        [wirteFileHandle seekToEndOfFile]; //设置偏移量跳到文件的末尾
        [wirteFileHandle writeData:data]; //写入数据
        [wirteFileHandle closeFile]; //关闭文件

        //文件定位读取
        // 从中间读取文件一直读取到结尾
        NSFileHandle *readFileHandle =[NSFileHandle fileHandleForReadingAtPath:path];
        if (readFileHandle == nil) {
            NSLog(@"读取失败");
        }

        //获取文件的总长度
        NSFileManager *fileManager =[NSFileManager defaultManager];
        NSDictionary *dic =[fileManager attributesOfItemAtPath:path error:nil];
        NSLog(@"dic : %@",dic);

        NSNumber *number =[dic objectForKey:NSFileSize];
        int  length = [number intValue];
        NSLog(@"length = %d", length);

        //设置文件读取的偏移量
        [readFileHandle seekToFileOffset:length/2];
        NSData *readData =[readFileHandle readDataToEndOfFile];//读到结尾
        //从开始读取文件一直读取到某一位置
        // - (NSData *)readDataOfLength:(NSUInteger)length;

        NSString*readStr =[[NSString alloc]initWithData:readData encoding:NSUTF8StringEncoding];

        NSLog(@"readStr : %@",readStr);
        [readFileHandle closeFile];
    }
    return 0;
}

当存储完数据后,因业务需求,需要改变数据存储的位置,我们就需要对文件进行移动或删除等操作。

//
//  main.m
//  NSFileManager
//
//  Created by hhg on 15/5/28.
//  Copyright (c) 2015年 hhg. All rights reserved.
//

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool
    {
        //创建NSFileManager对象 用类方法来创建文件
        NSFileManager * file = [NSFileManager defaultManager];
        NSString *str = @"对一个文件操作";
        //字符串转换为二进制数据
        NSData * data = [str dataUsingEncoding:NSUTF8StringEncoding];

        //创建一个文件并且写入数据
        NSString *home = NSHomeDirectory();
        NSString *path = [home stringByAppendingPathComponent:@"file.txt"];
        [file createFileAtPath:path contents:data attributes:nil];
        NSLog(@"主目录 = %@", home);

        /* ______________创建文件夹_____________   */

        NSString *folderPath = @"/Users/hhg/Desktop/myFolder";
        BOOL isSuccess =[file createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
        if (isSuccess) {
            NSLog(@"文件夹创建成功");
        }

        /*___________读取文件__________*/
        //读取二进制数据
        NSData *readData =[file contentsAtPath:path];
        //将二进制数据转码
        NSString *readStr =[[NSString alloc]initWithData:readData encoding:NSUTF8StringEncoding];

        NSLog(@"读取文件的内容:  %@",readStr);
        /* __________文件的移动复制剪切______________   */
        //移动
        NSString *movePath = @"/Users/hhg/Desktop/myFolder/file.txt";
        BOOL isMove = [file moveItemAtPath:path toPath:movePath error:nil];

        if (isMove) {
            NSLog(@"文件移动成功");
        }

        //文件复制
        [file copyItemAtPath:movePath  toPath:folderPath error:nil];
        /* _________文件的删除____________*/
        BOOL isDelete =  [file fileExistsAtPath:movePath];
        if ( isDelete ) {
//            [file removeItemAtPath:movePath  error:nil];
        }

        NSDictionary *dic = [file attributesOfItemAtPath:movePath error:nil];
        NSNumber *num = [dic objectForKey:NSFileSize];
        NSLog(@"字典:%@", dic);
        NSLog(@" 尺寸大小:%@", num);
        //-->创建文件夹->创建文件(写入字符串)-> 移动文件 ->读取文件内容->删除文件

    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/csdn_hhg/article/details/80458646
今日推荐