zoukankan      html  css  js  c++  java
  • Object C学习笔记25-文件管理(一)

        在此篇文章中简单记录一下文件管理,在Object C中NSFileManager用于管理文件已经路径。在Object C中的文件路径可以是相对路径也可以是绝对路径。斜线“/”开头,斜线实际上就是一个目录,称为 根目录。字符(~)用作用户主目录的缩写。点“ . ”表示当前目录,两点“  .. ”表示父目录。

      一. 创建NSFileManager 对象

        NSFileManager非常简单,可以使用如下方式来创建NSFileManager对象。

    NSString* fileName=[[NSString alloc] initWithFormat:@"/Users/username/Desktop/test.txt"];
    NSFileManager *fileManager=nil;
    fileManager=[NSFileManager defaultManager];

     二. 判断文件是否存在

        使用fileExistsAtPath判断某个文件是否存在,上面已经所过了,可以使用绝对路径 也可以使用相对路径

    if([fileManager fileExistsAtPath:fileName]==YES){
         NSLog(@"该文件存在");
    }else{
         NSLog(@"该文件不存在");
    }

     三. 拷贝文件

        使用函数copyPath:(NSString*) toPath(NSString*) 来拷贝一个文件,拷贝文件可以重新命名一个文件名称

     NSString* fileName=[[NSString alloc] initWithFormat:@"/Users/username/Desktop/test-new.txt"];
     NSLog(@"%d",[fileManager fileExistsAtPath:toFileName]);
     [fileManager copyPath:fileName toPath:toFileName handler:nil];
      if([fileManager fileExistsAtPath:toFileName]==YES){
          NSLog(@"该文件存在");
     }else{
          NSLog(@"该文件不存在");

      四. 判断文件内容是否相等

    if([fileManager contentsEqualAtPath:fileName andPath:toFileName]){
       NSLog(@"文件内容相同");
    }else{
       NSLog(@"文件内容不一样");
    }

      五. 重命名文件

    NSString* fileName=[[NSString alloc] initWithFormat:@"/Users/username/Desktop/test-new.txt"];
    [fileManager movePath:toFileName toPath:newFileName handler:nil];

      六. 获得文件属性

    NSDictionary *dic= [fileManager fileAttributesAtPath:newFileName traverseLink:NO];
     for (NSString *key in[dic keyEnumerator]) {
          NSLog(@"====== %@=%@",key,[dic valueForKey:key]);
     }

        使用方法fileAttributesAtPath 获得某个路径下的文件的属性,返回值是一个NSDictionary. 以上代码输出得到如下:

    2018-12-10 20:53:20.652818+0800 HelloWold[10766:1318694] ===== NSFileSystemNodes=9223372036854775807
    2018-12-10 20:53:20.652849+0800 HelloWold[10766:1318694] ===== NSFileSystemSize=500068036608
    2018-12-10 20:53:20.652880+0800 HelloWold[10766:1318694] ===== NSFileSystemFreeSize=234947850240
    2018-12-10 20:53:20.652893+0800 HelloWold[10766:1318694] ===== NSFileSystemFreeNodes=9223372036851745898
    2018-12-10 20:53:20.652907+0800 HelloWold[10766:1318694] ===== NSFileSystemNumber=16777220

      七. 删除文件

    [fileManager removeFileAtPath:newFileName handler:nil];

        通过方法removeFileAtPath 可以删除文件

       八. 获取文件内容

    NSString *content=[NSString stringWithContentsOfFile:fileName encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@",content);
  • 相关阅读:
    八款常用的 Python GUI 开发框架推荐
    scrapy + mogoDB 网站爬虫
    tkinter界面卡死的解决办法
    通过核心API启动单个或多个scrapy爬虫
    爬虫怎样绕过验证码?
    Python爬虫入门教程 33-100 电影评论数据抓取 scrapy
    Python开发 之 Websocket 的使用示例
    StringBuffer详解
    其实python正则表达式就这样简单明了
    ABAP和Java里的单例模式攻击
  • 原文地址:https://www.cnblogs.com/jiuyi/p/10098019.html
Copyright © 2011-2022 走看看