代码改变世界

iOS 文件读写

2013-04-16 15:27  waddell  阅读(229)  评论(0编辑  收藏  举报
-(void)writeToFile :(NSString *)content path:(NSString *)path{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    // 获取document路径
    NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [directoryPaths objectAtIndex:0];
    
    NSString *filePath = [documentDirectory stringByAppendingPathComponent:path];
    
    if (![fileManager fileExistsAtPath:filePath]) {
        // 转换数据 
        NSData *_content = [content dataUsingEncoding:NSUTF8StringEncoding];
        // 创建文件,并保存文件
        [fileManager createFileAtPath:filePath contents:_content attributes:nil];
    } else {
        NSFileHandle *outFile ;
        NSData *buffer;
        outFile = [NSFileHandle fileHandleForReadingAtPath:filePath];
        if (outFile == nil) {
            NSLog(@"Open of file for writing failed");
        }
        [outFile seekToEndOfFile];
        NSString *bs = [NSString stringWithFormat:@"%@", content];
        buffer = [bs dataUsingEncoding:NSUTF8StringEncoding];
        [outFile writeData:buffer];
        [outFile closeFile];
    }
}