2013-07-19 文件操作

代码:


    //init方法、便利构造器  这是OC中初始化对象的两种方法

 

     NSString *path1= @"/Users/1010/Desktop/abc.txt";

    //用一个文件来初始化一个字符串,也就是读文件中的内容

    NSError *error = nil;

   // NSString *content1 = [[NSString alloc]initWithContentsOfFile:path1 encoding:NSUTF8StringEncoding error:&error];

    NSString *content1 = [NSString stringWithContentsOfFile:path1 encoding:4 error:&error];

    if (error != nil)

    {

        NSLog(@"file:%@",[error localizedFailureReason]);

    }

    NSLog(@"content1 = %@",content1);

    

    //写文件,它会覆盖掉文件中以前的内容

    NSString *str1 = @"i am learning ios";

    BOOL s =  [str1 writeToFile:path1

                     atomically:YES

                       encoding:4

                          error:&error];//atomically 若为no,则str1会立刻写入到文件中,若为YES,则先写入到缓存中,当该文件为空闲的时候,在从缓存写入到文件中

    NSLog(@"s = %d",s);

    

    

 //   NSData *data1 = [[NSData alloc]initWithContentsOfFile:path1];//init初始化

    NSData *data1 = [NSData dataWithContentsOfFile:path1];//便利构造器初始化

    NSLog(@"data1 = %@",data1);

    

    NSString *str2 = [[NSString alloc]initWithData:data1 encoding:4];//encoding:4,4代表UTF-8编码

    NSLog(@"str2 = %@",str2);

     

    NSString *path2 = @"http://www.baidu.com/img/bdlogo.gif";//网络上的一张图片的地址

    NSURL *url = [NSURL URLWithString:path2];//将字符串转换成url

    NSData *imgData = [NSData dataWithContentsOfURL:url];

    UIImage *img = [UIImage imageWithData:imgData];

    

    [imgData writeToFile:@"/Users/1010/Desktop/logo.gif" atomically:YES]; //NSData虽然是二进制的,但是可以写入到文件中

    

    

    CGRect r = CGRectMake(100100100100);//ios中的屏幕是绝对定位

    UIImageView *_imgView = [[UIImageView alloc]initWithFrame:r];

    _imgView.image = img;

    [self.window addSubview:_imgView];

    

    //文件管理

    

    NSFileManager *fm = [NSFileManager defaultManager];//文件管理工具是一个单例

 //   [fm createDirectoryAtPath:@"/Users/1010/Desktop/abc/123" withIntermediateDirectories:YES attributes:nil error:nil];

    //withIntermediateDirectories 是否创建中间目录123

    //attributes文件袋额属性,只读等等权限一类的东西

    

  //  [fm createFileAtPath:@"/Users/1010/Desktop/abc/123/logo.gif" contents:imgData attributes:nil];//在某个路径下创建内容为.....的文件

   // [fm removeItemAtPath:@"/Users/1010/Desktop/abc/123/logo.gif" error:nil];

   

    NSString *oriPath = @"/Users/1010/Desktop/abc/123/logo.gif";

    NSString *targetPath = @"/Users/1010/Desktop/abc/logo.gif";

    [fm moveItemAtPath:oriPath toPath:targetPath error:nil];

 

    //

    NSString *bundleStr = [[NSBundle mainBundlepathForResource:@"abc" ofType:@"txt"];//mainBundle这是一个单例

    NSLog(@"bundleStr = %@",bundleStr);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值