您当前的位置:首页 > 建站知识 > 编程知识

OC 读写文件

发布时间: 2020-01-14 │ 浏览:269 

/*

 读取member.txt文件

 */

NSString* readTxt()

{

    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;

    NSString *filePath=[NSString stringWithFormat:@"%@%@",documentPath,@"/member.txt"];


    NSData *data =[[NSData alloc]initWithContentsOfFile:filePath];

    

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

    

    return readStr;

}


/*

写入member.txt文件

*/

void wirteTxt(NSString *txt){

    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;

    NSString *filePath=[NSString stringWithFormat:@"%@%@",documentPath,@"/member.txt"];

    

    BOOL isWriteString =[txt writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

    

    if (isWriteString) {

        NSLog(@"txt文件写入成功");

        

    }else{

        NSLog(@"txt文件写入失败");

    };

    

    return;

}


//调用

-(void)viewDidAppear:(BOOL)animated{

    wirteTxt(@"意飞iOS");

    NSString *sTxt=readTxt();

    NSLog(@"%@",sTxt);

}