NSFileManger

//创建文件管理器

NSFileManager *fileManager = [NSFileManagerdefaultManager];

//指向文件目录

(1)        NSString *path = [NSHomeDirectory()stringByAppendingPathComponent:@"Documents"];

(2)        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

NSString *path = [paths objectAtIndex:0];

//在指定的目录下创建一个文件夹

[fileManager createDirectoryAtPath: [NSStringstringWithFormat:@"%@/myFolder", path]attributes:nil];

//获取一个目录内的文件及文件夹列表

(1)  NSError *error = nil;

    NSArray *fileList = [[NSArrayalloc] init];

   fileList = [[NSFileManager defaultManager]     contentsOfDirectoryAtPath:patherror:&error];

(2) NSDirectoryEnumerator *direnum = [[NSFileManagerdefaultManager] enumeratorAtPath:path];

    NSArray *fileList =[direnumallObjects];

//更改到待操作的目录下

[fileManager changeCurrentDirectoryPath:[path stringByExpandingTildeInPath]];

//创建文件

NSString *fileName = @"test.txt";

NSString *filePath = [path stringByAppendingPathComponent:fileName];

[fileManager createFileAtPath:filePathcontents:nilattributes:nil];

//判断文件是否存在

[fileManager fileExistsAtPath:filePath];

//删除文件

[fileManager removeItemAtPath:filePatherror:nil];

//根据文件名获取文件路径

NSString *filePath = [[NSBundlemainBundle] pathForResource:fileNameofType:nil];

 

//字符串写入文件

NSString *str1 = @"hello world !";

[str1 writeToFile: filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];


//data写入文件   

//待写入的数据

NSString *temp = @"Hello world !";

int data0 = 100000;

float data1 = 23.45f;

//创建数据缓冲

NSMutableData *writer = [[NSMutableData alloc] init];

//将字符串添加到缓冲中

[writer appendData:[tempdataUsingEncoding: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:[readersubdataWithRange:NSMakeRange(0, [temp length])]

 encoding:NSUTF8StringEncoding];

[reader getBytes:&gData0 range:NSMakeRange([templength], sizeof(gData0))];

[reader getBytes:&gData1 range:NSMakeRange([templength] + sizeof(gData0), sizeof(gData1))];

 

NSLog(@"gData0:%@ gData1:%i gData2:%f", gData2, gData0, gData1);

 

//从路径中获得完整的文件名(带后缀)

NSString *fileName =[filePathlastPathComponent];

//获得文件名(不带后缀)

NSString *fileName1 = [fileNamestringByDeletingPathExtension];

 //获得文件的扩展名(不带.)

NSString *fileName2 = [fileNamepathExtension];


你可能感兴趣的:(ios,NSFileManger)