IOS 读写文件

本文介绍了一种在iOS设备上进行文件读写的实现方法,通过使用NSFileManager进行文件路径的获取和文件的操作,包括文件的创建、删除及读取。
iphone可以很容易的实现文件的读写,但是如果你没有使用苹果公司99美元开发者sdk的话,你利用破解打出来的api包,安装到手机上不能把文件写入手机.下面是我实现读写的代码:     #import "ManagerFile.h"



    @implementation ManagerFile



    -(void)writeFile:(NSString *)file

    {

        //创建文件管理器

        NSFileManager *fileManager = [NSFileManager defaultManager];

        //获取路径

        //参数NSDocumentDirectory要获取那种路径

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

        NSString *documentsDirectory = [paths objectAtIndex:0];//去处需要的路径   

        //更改到待操作的目录下

        [fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]];

        //创建文件fileName文件名称,contents文件的内容,如果开始没有内容可以设置为nil,attributes文件的属性,初始为nil

        //获取文件路径

        [fileManager removeItemAtPath:"username" error:nil];

        NSString *path = [documentsDirectory stringByAppendingPathComponent:"username"];

        //创建数据缓冲

        NSMutableData *writer = [[NSMutableData alloc] init];

        //将字符串添加到缓冲中

        [writer appendData:[file dataUsingEncoding:NSUTF8StringEncoding]];

        //将其他数据添加到缓冲中

        //将缓冲的数据写入到文件中

        [writer writeToFile:path atomically:YES];

        [writer release];

    }

    -(NSString *)readFile

    {

        //创建文件管理器

        NSFileManager *fileManager = [NSFileManager defaultManager];

        //获取路径

        //参数NSDocumentDirectory要获取那种路径

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

        NSString *documentsDirectory = [paths objectAtIndex:0];//去处需要的路径   

        //更改到待操作的目录下

        [fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]];

        //获取文件路径

        NSString *path = [documentsDirectory stringByAppendingPathComponent:"username"];

        NSData *reader = [NSData dataWithContentsOfFile:path];

        return [[NSString alloc] initWithData:reader

                                     encoding:NSUTF8StringEncoding];

    }

    @end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值