zoukankan      html  css  js  c++  java
  • NSFileManager的简单实用

    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        
    //    NSFileManager简单使用,文件管理类
    //    1.创建对象 使用defaultManager类方法,创建单例对象(系统的单例还有NSUserDefaults, NSNotification, UIApplication,NSURLCache);
        
        NSFileManager *fileManger = [NSFileManager defaultManager];
        //创建文件夹,将要创建的/path1/path2/文件拼接到路径中
        //获取Documents路径
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentPath = [paths objectAtIndex:0];
        NSLog(@"path:%@", documentPath);
        
        NSString *newPath1 = [documentPath stringByAppendingPathComponent:@"path1"];
        
        [fileManger createDirectoryAtPath:newPath1 withIntermediateDirectories:YES attributes:nil error:nil];
        //创建文件夹里面的文件
        NSString *filePath1 = [newPath1 stringByAppendingPathComponent:@"text.txt"];
        
        
        BOOL file = [fileManger createFileAtPath:filePath1 contents:nil attributes:nil];
        
        if (file) {
            NSLog(@"文件创建成功");
        }else{
            NSLog(@"文件创建失败");
        }
        
        //往文件里面写入(也可以写入字典,数组等)
        NSString *strData = @"想要写入的东西";
        
        BOOL write = [strData writeToFile:filePath1 atomically:YES encoding:NSUTF8StringEncoding error:nil];
        
        if (write) {
            NSLog(@"写入成功");
        }else{
            NSLog(@"写入失败");
        }
        
        //判断文件是否存在
        if ([fileManger fileExistsAtPath:filePath1]) {
            
            NSLog(@"存在该文件");
            
        }else{
            NSLog(@"不存在该文件");
        }
        
        //删除文件
        BOOL delete = [fileManger removeItemAtPath:filePath1 error:nil];
        
        if (delete) {
            
            NSLog(@"文件删除成功");
        }else{
            NSLog(@"文件删除失败");
        }
        
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    @end
  • 相关阅读:
    使用FileReader在浏览器读取预览文件(image和txt)
    移动端Vue图片获取,压缩,预览组件-upload-img(H5+获取照片,压缩,预览)
    文件(图片)转base64
    Vue单页面应用打包app处理返回按钮
    hbuilder/hbuilderx 无法检测到模拟器
    不启动AndroidStudio直接启动其模拟器
    ES6,箭头函数 (=>)注意点
    ES6,扩展运算符
    strcmp使用注意
    android11 gc5035前置摄像头当作后置使用左右镜像问题
  • 原文地址:https://www.cnblogs.com/LzwBlog/p/5744534.html
Copyright © 2011-2022 走看看