• 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];
  • 相关阅读:
    集合容器概述
    enum枚举类型
    this关键字、this()、super()
    重载与重写
    nginx报404的可能错误
    nginx常用命令
    vbs系统监控
    VBS windows监控
    Oracle SQL优化[转]
    shell /bin/bash^M: bad interpreter错误解决
  • 原文地址:https://www.cnblogs.com/huen/p/3535154.html
Copyright © 2020-2023  润新知