ios 读写文件-复习篇

//创建文件管理器
NSFileManager   *fileManager   =   [ NSFileManager   defaultManager ] ;
//获取路径
//参数NSDocumentDirectory要获取那种路径
NSArray   *paths   =   NSSearchPathForDirectoriesInDomains ( NSDocumentDirectory , NSUserDomainMask ,   YES ) ;
NSString   *documentsDirectory   =   [ paths  objectAtIndex : 0 ] ;
 
//更改到待操作的目录下
[ fileManager  changeCurrentDirectoryPath : [ documentsDirectory  stringByExpandingTildeInPath ] ] ;
 
//创建文件fileName文件名称,contents文件的内容,如果开始没有内容可以设置为nil,attributes文件的属性,初始为nil
[ fileManager  createFileAtPath : @"fileName"  contents :nil  attributes :nil ] ;
 
//删除待删除的文件
[ fileManager  removeItemAtPath : @"createdNewFile"  error :nil ] ;

写入数据:

//获取文件路径NSString *path = [documentsDirectory stringByAppendingPathComponent:@"fileName"];//待写入的数据NSString *temp = @”Welcome to blog.iosxcode4.com”;int data0 = 100000;float data1 = 23.45f;//创建数据缓冲NSMutableData *writer = [[NSMutableData alloc] init];//将字符串添加到缓冲中[writer appendData:[temp dataUsingEncoding:NSUTF8StringEncoding]];//将其他数据添加到缓冲中[writer appendBytes:&data0 length:sizeof(data0)];[writer appendBytes:&data1 length:sizeof(data1)];//将缓冲的数据写入到文件中[writer writeToFile:path atomically:YES];[writer release];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//获取文件路径
NSString   *path   =   [ documentsDirectory stringByAppendingPathComponent : @"fileName" ] ;
 
//待写入的数据
NSString   *temp   =   @ Welcome   to  blog . iosxcode4 . com ;
int   data0   =   100000 ;
float   data1   =   23.45f ;
 
//创建数据缓冲
NSMutableData   *writer   =   [ [ NSMutableData   alloc ]  init ] ;
 
//将字符串添加到缓冲中
[ writer  appendData : [ temp dataUsingEncoding :NSUTF8StringEncoding ] ] ;
 
//将其他数据添加到缓冲中
[ writer  appendBytes : & data0  length :sizeof ( data0 ) ] ;
[ writer  appendBytes : & data1  length :sizeof ( data1 ) ] ;
 
//将缓冲的数据写入到文件中
[ writer  writeToFile :path  atomically :YES ] ;
[ writer  release ] ;

读取数据:

int gData0;float gData1;NSString *gData2;NSData *reader = [NSData dataWithContentsOfFile:path];gData2 = [[NSString alloc] initWithData:[reader subdataWithRange:NSMakeRange(0, [temp length])]encoding:NSUTF8StringEncoding];[reader getBytes:&gData0 range:NSMakeRange([temp length], sizeof(gData0))];[reader getBytes:&gData2 range:NSMakeRange([temp length] + sizeof(gData0), sizeof(gData1))];NSLog(@”gData0:%@ gData1:%i gData2:%f”, gData0, gData1, gData2);
1
2
3
4
5
6
7
8
9
10
11
int   gData0 ;
float   gData1 ;
NSString   *gData2 ;
 
NSData   *reader   =   [ NSData  dataWithContentsOfFile :path ] ;
gData2   =   [ [ NSString   alloc ]  initWithData : [ reader  subdataWithRange :NSMakeRange ( 0 ,   [ temp  length ] ) ]
encoding :NSUTF8StringEncoding ] ;
[ reader  getBytes : & gData0  range :NSMakeRange ( [ temp  length ] ,   sizeof ( gData0 ) ) ] ;
[ reader  getBytes : & gData2  range :NSMakeRange ( [ temp  length ]   +   sizeof ( gData0 ) , sizeof ( gData1 ) ) ] ;
 
NSLog ( @ gData0 : % @   gData1 : % i  gData2 : % f ,   gData0 ,   gData1 ,   gData2 ) ;

你可能感兴趣的:(ios,文件管理器)