zoukankan      html  css  js  c++  java
  • NSFileManager、NSFileHandle

     NSFileSManager:目录文件管理

    #import "AppDelegate.h"
    #define ERROR(a) if(a){NSLog(@"%@",a);exit(-1);}
    #define PATH @"/Users/huen/Desktop/NSManage"
    @implementation AppDelegate
        NSError *error = nil;
        NSFileManager *fm = [NSFileManager defaultManager];//单例对象
        /*
        NSArray *arr = [fm contentsOfDirectoryAtPath:PATH error:&error];//浅度遍历目录
        ERROR(error);//若上句报错,打印错误,退出程序
        NSLog(@"%@",arr);
        arr = [fm subpathsOfDirectoryAtPath:PATH error:&error];//深度遍历目录
        ERROR(error);//若上句报错,打印错误,退出程序
        NSLog(@"%@",arr);
        */
        //创建目录
        [fm createDirectoryAtPath:[NSString stringWithFormat:@"%@/middle/dir",PATH]
      withIntermediateDirectories:YES//支持创建middle文件
                       attributes:nil
                            error:&error];
        ERROR(error);
        //创建文件
        [fm createFileAtPath:[NSString stringWithFormat:@"%@/middle/dir/file.rtf",PATH]
                    contents:[@"hello" dataUsingEncoding:NSUTF8StringEncoding]
                  attributes:nil];
        ERROR(error);
        //
        [fm copyItemAtPath:[NSString stringWithFormat:@"%@/middle/dir/file.rtf",PATH]
                    toPath:[NSString stringWithFormat:@"%@/middle/file.rtf",PATH]
                     error:&error];
        ERROR(error);
        
        [fm moveItemAtPath:[NSString stringWithFormat:@"%@/middle/dir",PATH]
                    toPath:[NSString stringWithFormat:@"%@/dir",PATH]
                     error:&error];
        ERROR(error);
        //删除
    //    [fm removeItemAtPath:[NSString stringWithFormat:@"%@/middle/file.rtf",PATH]
    //                   error:&error];
    //    ERROR (error);

    NSFileHandle:文件读写操作

        //文件写
        NSFileHandle *fhw = [NSFileHandle fileHandleForWritingAtPath:@"/Users/huen/Desktop/document.rtf"];
        //[fhw truncateFileAtOffset:0];//覆盖写
        [fhw seekToEndOfFile];//追加
        
        [fhw writeData:[@"xxx is a good man" dataUsingEncoding:NSUTF8StringEncoding]];
       [fhw closeFile];
    //文件读 NSFileHandle *fh = [NSFileHandle fileHandleForReadingAtPath:@"/Users/huen/Desktop/document.rtf"]; NSData *data = [fh readDataToEndOfFile]; NSString *s = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",s);
      [fh closeFile];
  • 相关阅读:
    nginx+upsync+consul 构建动态nginx配置系统
    服务容错保护断路器Hystrix之六:缓存功能的使用
    consul之:ACL配置使用
    Consul之:服务健康监测
    Consul实践指导-DNS接口
    Spring 整合Mybatis实例
    ORACLE SEQUENCE 具体解释
    python高速排序
    降阶法计算行列式方法有个地方有Bug(原文也已更正,此为更正后部分)
    MyBatis在Oracle中插入数据并返回主键的问题解决
  • 原文地址:https://www.cnblogs.com/huen/p/3535154.html
Copyright © 2011-2022 走看看