IOS基础知识记录六(读写文件)

ios对文件的读写
NSString *filePath = @"/User/test.txt"
//判断文件是否存在, 否则创建该文件
if (![[NSFileManager alloc] fileExistsAtPath: filePath]) {
        //contents 可以初始化文件时, 加入默认内容
        [[NSFileManager alloc] createFileAtPath: filePath
                                       contents: nil attributes: nil];
    }

//更新文件
NSFileHandle *handler = [NSFileHandle fileHandleForUpdatingAtPath: filePath];
    [handler seekToEndOfFile];//跳到文件末尾
    
    NSString *content = @"this is a file." 
    [handler writeData: [content dataUsingEncoding: NSUTF8StringEncoding]];
    [handler closeFile];


//读取文件
  if ([[NSFileManager alloc] fileExistsAtPath: filePath]) {
        NSFileHandle *handler = [NSFileHandle fileHandleForReadingAtPath: filePath];
       
        //content读取的新内容
        NSString *content = [[NSString alloc] initWithData: [handler availableData] encoding: NSUTF8StringEncoding];
        
        [handler closeFile];
    }


[handler closeFile];//文件读写后,关闭文件

猜你喜欢

转载自lihao312.iteye.com/blog/1715259