[iOS基础]文件读取详解

文件操作

创建文件夹:
 NSString *imageDir = [NSString stringWithFormat:@"%@/Caches/%@", NSHomeDirectory(), dirName];
 BOOL isDir = NO;
 NSFileManager *fileManager = [NSFileManager defaultManager];
 BOOL existed = [fileManager fileExistsAtPath:imageDir isDirectory:&isDir];
 if ( !(isDir == YES && existed == YES) )
 {
  [fileManager createDirectoryAtPath:imageDir withIntermediateDirectories:YES attributes:nil error:nil];
 }


删除文件夹及文件级内的文件:
 NSString *imageDir = [NSString stringWithFormat:@"%@/Caches/%@", NSHomeDirectory(), dirName];
 NSFileManager *fileManager = [NSFileManager defaultManager];
 [fileManager removeItemAtPath:imageDir error:nil];

文件读写解析

http://blog.csdn.net/diqun1314/article/details/7245501
http://3lian.com/edu/2013/10-14/101565.html

读取txt文件

 NSString *tmp;
        NSArray *lines; /*将文件转化为一行一行的*/
        lines = [[NSString    stringWithContentsOfFile:@"testFileReadLines.txt"]
                       componentsSeparatedByString:@"\n"];

         NSEnumerator *nse = [lines objectEnumerator];

         // 读取<>里的内容
         while(tmp = [nse nextObject]) {
                  NSString *stringBetweenBrackets = nil;
                  NSScanner *scanner = [NSScanner scannerWithString:tmp];
                  [scanner scanUpToString:@"<" intoString:nil];
                  [scanner scanString:@"<" intoString:nil];
                  [scanner scanUpToString:@">" intoString:&stringBetweenBrackets];
                  NSLog([stringBetweenBrackets description]);
          }

文件读取的四种方法

//第一种方法: NSFileManager实例方法读取数据
        NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES);
        NSString* thepath = [paths lastObject];
        thepath = [thepath stringByAppendingPathComponent:@"fd_list.txt"];
        NSLog(@"桌面目录:%@", thepath);
        NSFileManager* fm = [NSFileManager defaultManager];
        NSData* data = [[NSData alloc] init];
        data = [fm contentsAtPath:thepath];
        NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);


        //第二种方法: NSData类方法读取数据
        data = [NSData dataWithContentsOfFile:thepath];
        NSLog(@"NSData类方法读取的内容是:%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);


        //第三种方法: NSString类方法读取内容
        NSString* content = [NSString stringWithContentsOfFile:thepath encoding:NSUTF8StringEncoding error:nil];
        NSLog(@"NSString类方法读取的内容是:\n%@",content);


        //第四种方法: NSFileHandle实例方法读取内容
        NSFileHandle* fh = [NSFileHandle fileHandleForReadingAtPath:thepath];
        data = [fh readDataToEndOfFile];
        NSLog(@"NSFileHandle实例读取的内容是:\n%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页