Objective-C_语言_文件管理

#import "ViewController.h"


@interface ViewController ()


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    

//    NSString *string=[NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.baidu.com"] encoding:NSUTF8StringEncoding error:nil];

//    NSLog(@"%@",string);

    

    /*

     IOS文件读写

     当第一次启动app时,ios操作系统就为此app创建了一个文件系统,该文件系统下默认有四个目录

     ,分别为:

     

     Documents:存储用户在操作app时产生的数据,次目录下的数据可以通过iCloud进行同步

     Library:用户偏好设置数据,通常和此类NSUserDefaults搭配使用,此目录下的数据可以通过iCloud进行同步

     tmp:存放临时数据,此目录下的数据不会通过iCloud同步

     

     app:开发者不会操作此目录,通常是通过 NSBundle类获取包类资源,如工程素材。

     

     */

  


    //获取程序根目录


    NSString *rootPath=NSHomeDirectory();

    //获取程序下目录下的Documents

    NSString *documentsPath=[rootPath stringByAppendingFormat:@"/%@",@"Documents"];

    //或者

    documentsPath=[rootPath stringByAppendingPathComponent:@"Documents"];

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

    

    //常用的获取Documents目录的方式

    

    /*

     <#NSSearchPathDirectory directory#>:指定了搜索的路径名称

     <#NSSearchPathDomainMask domainMask#>:限定了文件的检索范围只在沙盒(sandbox)内部

     <#BOOL expandTilde#>:决定了师傅展开波浪线符号,展开后才是完整的路径,者个布尔值

     

     该方法返回的为一个数组,在iphone中由只有一个唯一路径,所有直接取数组第一个元素即可

     */

 

    

    documentsPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectoryNSUserDomainMaskYES)objectAtIndex:0];

    

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

   



   

    //下载一个视频文件到Documents目录下的Video文件夹


    

    //这里我们封装一个函数,使得这个函数返回的时我们在Documents目录下向要的文件夹的路径

    

    NSString *videoPath=[self creatDirInDocuments:@"Video"];//创建一个函数用来创建一个文件夹

    

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

    

    /*

     

     */

    if (videoPath!=nil)

    {

        NSFileManager *fileManager=[NSFileManager defaultManager];

        /*

         http://v8.tv.cctv5.cctv.com/r5wbth/4d/e7/4de76971-63f4-4717-f28b-03d757a7704f/mp4h.mp4

         */

        NSString *videoUrlString=@"";//网址

        

        NSString *fileVideo=[videoPath stringByAppendingPathComponent:[videoPath lastPathComponent]];//取字符串最后一个斜杠后面的字符串,在拼接起来。

        

        //如果文件夹不存在该路径

        if (![fileManager fileExistsAtPath:fileVideo])

        {

            //9.0以前才用这个

            //[videoUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

        

            //进行编码

            NSCharacterSet *characterSet=[NSCharacterSet URLQueryAllowedCharacterSet];

            videoUrlString=[videoUrlString stringByAddingPercentEncodingWithAllowedCharacters:characterSet];

            

            //网络  我们的图片,视频,音频等在网络中都是一二进制文件传输,所有这里我们那到得是data

            NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:videoUrlString]];

            

            //判断data是否为空

            if (data==nil)

            {

                NSLog(@"网络不给力,请稍后再试");

            }

            else

            {

            

            //用单例类NSFileManager的对象,将文件写入本地  格式化快捷键为Ctrl+i

                BOOL isSuccess=[fileManager createFileAtPath:fileVideo contents:data attributes:nil];

                if (isSuccess)

                {

                    NSLog(@"视频下载成功");

                }

                else

                {

                    NSLog(@"视频下载失败");

                }

            }

            

        }

        

    }

    



 

    //字符串拼接,获取Library目录

    NSString *libraryPath=[rootPath stringByAppendingString:@"/Library"];

    NSLog(@"%@",rootPath);

    

    libraryPath=[NSSearchPathForDirectoriesInDomains(NSLibraryDirectoryNSUserDomainMaskYES)objectAtIndex:0];

    

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

    

    



 

    //tmp文件

    

    

    NSString * tmpString=NSTemporaryDirectory();

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

    

//    NSArray *imgsArray1 = @[@"http://img0.imgtn.bdimg.com/it/u=4149130001,3742834577&fm=11&gp=0.jpg",@"http://img4.imgtn.bdimg.com/it/u=3559701691,1695542011&fm=11&gp=0.jpg",@"http://img2.imgtn.bdimg.com/it/u=1586092343,2404972431&fm=11&gp=0.jpg",@"http://img0.imgtn.bdimg.com/it/u=2476766911,2700008511&fm=11&gp=0.jpg"];

    

    NSArray *imgsArray =@[@"http://d.hiphotos.baidu.com/image/pic/item/6a63f6246b600c331c964cf21d4c510fd9f9a119.jpg",@"http://c.hiphotos.baidu.com/image/pic/item/023b5bb5c9ea15ce9c017233b1003af33a87b219.jpg",@"http://f.hiphotos.baidu.com/image/pic/item/e1fe9925bc315c60d916f9d58ab1cb134954770d.jpg",@"http://h.hiphotos.baidu.com/image/pic/item/30adcbef76094b366b2389d7a4cc7cd98d109d53.jpg",@"http://d.hiphotos.baidu.com/image/pic/item/b17eca8065380cd72aaf30d7a644ad3459828153.jpg"];

    

    //下载一些图片放到tmp目录下的Imgs文件夹下,如果有些图片已经下载,那么不会继续下载。

    

    //返回一个带Imgs,这个类下的tmp文件是否有Imgs

    NSString *imgsTmpPath=[self creatDirInTmp:@"Imgs"];

    

    if (imgsTmpPath!=nil)

    {

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

        

        for (int i=0; i<imgsArray.count; i++)

        {

            NSString *imgsString=[imgsArray[i] lastPathComponent];

            

            //获得每张图片的路径

            NSString *imgsPath=[imgsTmpPath stringByAppendingPathComponent:imgsString];

            

            NSFileManager *fileManage=[NSFileManager defaultManager];

            if(![fileManage fileExistsAtPath:imgsPath])

            {

                NSString *urlString=[imgsArray[i]stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

                

                //urlString转化成data

                

                NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];

                

                if (data==nil)

                {

                    NSLog(@"网络有问题,请稍后再试");

                }

                else

                {

                    BOOL isSuccess=[data writeToFile:imgsPath atomically:YES];

                    

                    if (isSuccess)

                    {

                        NSLog(@"图片下载成功");

                    }

                    else

                    {

                        NSLog(@"图片下载失败");

                    }

                }

                

            }

        }

    }

    

  



    

//

//    //条件断点  断点右击Edit BreakPoint..->Action->点击一下-Log Message->在文本框内些@rootPath@

//    

//    for (int i=0; i<100; i++)

//    {

//        //条件断点  断点右击Edit BreakPoint..->Condition->写上i==10代表当i==10时停止循环->Action->点击一下-Log Message->在文本框内些@i@相当于输出1

//        

//        

//    }

    

    

    


   


   

    

    //NSLong变了棕色的

   



   

    //将字符串写入到本地

    

    NSString *targetString=@"Hello guys";

    

    BOOL flag=[targetString writeToFile:[imgsTmpPath stringByAppendingPathComponent:@"a.txt"atomically:YESencoding:NSUTF8StringEncoding error:nil];

    if (flag)

    {

        NSLog(@"字符串写入本地成功");

    }

    else

    {

        NSLog(@"字符串写入本地失败");

    }

     


 

    //将数字写入本地文件

    NSArray *array=@[@"aa",@"bb",@"cc",@"dd",@"ee"];

    flag=[array writeToFile:[imgsTmpPath stringByAppendingPathComponent:@"array.txt"atomically:YES];

    

    if (flag)

    {

        NSLog(@"数组写入成功");

    }

    else

    {

        NSLog(@"数组写入失败");

    }

     



 

    //将字典写入本地

    NSDictionary *dictionary=@{@"name":@"Rick",@"age":@25,@"addreaa":@"GZ"};

    

    flag=[dictionary writeToFile:[imgsTmpPath stringByAppendingPathComponent:@"dictionary.txt"atomically:YES];

    if (flag)

    {

        NSLog(@"字典写入成功");

    }

    else

    {

        NSLog(@"字典写入失败");

    }

       



    //计算文件大小

    //获得将要计算的文件夹

    

    NSFileManager *fileManage=[NSFileManager defaultManager];

    

    //获得imgs目录下文件名组成的数组

    

    NSArray *imgsFileArray=[fileManage subpathsAtPath:imgsTmpPath];

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

    

    

    CGFloat count=0;

    

    for (NSString *ele in imgsFileArray)

    {

        NSData *data=[NSData dataWithContentsOfFile:[imgsTmpPath stringByAppendingPathComponent:ele]];

        

        count +=data.length;

    }

    

    count=count/1024/1024;

    NSLog(@"缓存文件的大小为:%.2fM",count);

    



   

    //把一张图片放到文件路径

    

    //删除文件

//    for (NSString *ele in imgsFileArray)

//    {

//        BOOL isSuccess=[fileManage removeItemAtPath:[imgsTmpPath stringByAppendingPathComponent:ele] error:nil];

//        if (isSuccess)

//        {

//            NSLog(@"删除成功");

//        }

//        else

//        {

//            NSLog(@"删除失败");

//        }

//        

//    }

     



 

    //app,获取包内图片,显示在UI

    

    NSBundle *bundle=[NSBundle mainBundle];

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

    

    //<取里面了>

    

    NSString *imgpath=[bundle pathForResource:@"anglaybaby" ofType:@".jpg"];//png不用加“.”如果是JPG要加上‘.’pathForpesource:写文件名,ofType放类型

    NSData *data=[NSData dataWithContentsOfFile:imgpath];

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

}

   



//上面定义的类

-(NSString *)creatDirInTmp:(NSString *)dirName

{

    NSString *tmp=NSTemporaryDirectory();//获取Tmp文件夹路径

    

    //想要文件的路径

    NSString *dirPath=[tmp stringByAppendingPathComponent:dirName];

    

    NSFileManager *fileManager=[NSFileManager defaultManager];

    

    if (![fileManager fileExistsAtPath:dirPath])

    {

        //创建文件夹

        NSError *error;

        BOOL isSuccess=[fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nilerror:&error];

        if (!isSuccess)

        {

            dirPath=nil;

            NSLog(@"error=%@",error.debugDescription);

        }

    }

    return dirPath;

}


-(NSString *)creatDirInDocuments:(NSString *)dirName//想要创建文件夹名称

{

    //获得Documents的文件路径

    NSString *documents=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectoryNSUserDomainMaskYES)objectAtIndex:0];

    

    //拼接成我们想要文件的路径的字符串

    

    NSString *dirDocuments=[documents stringByAppendingPathComponent:dirName];

    

    //获取NSFileManager单例类,用于文件操作

    NSFileManager *fileManage=[NSFileManager defaultManager];

    

    //判断本地是否存在这个文件夹或某个文件

    BOOL isExist=[fileManage fileExistsAtPath:dirName];

    

    if (!isExist)//不存在

    {

        //创建文件夹

        

        /*

         第一个参数:文件路径

         */

        

        NSError *error;

        

        BOOL isSuccess=[fileManage createDirectoryAtPath:dirDocuments withIntermediateDirectories:YESattributes:nil error:&error];

        if(!isSuccess)

        {

            //如果文件创建失败,将打印错误的信息

            NSLog(@"error=%@",error.debugDescription);//打印错误信息

            dirDocuments=nil;

        }

    }

    return dirDocuments;

}




- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end

============================================================================

main.m

#import <UIKit/UIKit.h>

#import "AppDelegate.h"


int main(int argc, char * argv[]) {

    @autoreleasepool {

        return UIApplicationMain(argc, argv, nilNSStringFromClass([AppDelegate class]));

    }

}


=============================================================================

PCH文件宏定义文件

PrefixHeader.pch

#ifndef PrefixHeader_pch

#define PrefixHeader_pch


// Include any system framework and library headers here that should be included in all compilation units.

// You will also need to set the Prefix Header build setting of one or more of your targets to reference this file.


//A better version of NSLog


#define NSLog(format, ...) do { \

fprintf(stderr, "<%s : %d> %s\n", \

[[[NSString stringWithUTF8String:__FILE__]  lastPathComponent] UTF8String], \

__LINE__, __func__); \

(NSLog)((format), ##__VA_ARGS__); \

fprintf(stderr, "-------\n"); \

} while (0)


#endif /* PrefixHeader_pch */

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值