------
Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
文件的写入
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(@"paths%@",paths);
NSString *docDir = [paths objectAtIndex: 0];
if (!docDir) { //假值
NSLog(@"Documents 目录未找到");
}
NSArray *array = [[NSArrayalloc] initWithObjects:@"内容",@"content",nil];
NSString *filePath = [docDir stringByAppendingPathComponent:@"testFile.txt"];
[array writeToFile:filePath atomically:YES];//将array 写入 filePath路径提供的文件
文件的读取
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *filePath = [docDir stringByAppendingPathComponent:@"testFile.txt"];
NSArray *array = [[NSArrayalloc]initWithContentsOfFile:filePath];
NSLog(@"%@", array); //注意这里在输出时,中文会成为utf8格式的编码,如果使用消息方式不会
创建新目录以及在新目录下创建文件
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *doucumentsDirectory = [paths objectAtIndex: 0];
NSLog(@"%@",doucumentsDirectory);
NSFileManager *fileManager =[ NSFileManagerdefaultManager];
NSString *testDirectory = [doucumentsDirectory stringByAppendingPathComponent:@"test"];
[fileManager createDirectoryAtPath:testDirectory withIntermediateDirectories:YESattributes:Nilerror:Nil]; //创建test目录
NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test00.txt"];
NSString *string = @"写入内容,write String";
[fileManager createFileAtPath:testPath contents:[string dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];//创建文件以及写入内容
查看目录下所有文件
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex: 0];
NSFileManager *fileManage = [NSFileManagerdefaultManager];
NSString *myDirectory = [documentsDirectory stringByAppendingPathComponent:@"test"];
NSArray *file = [fileManage subpathsOfDirectoryAtPath:myDirectory error:nil];//和下面的方法一样
NSLog(@"%@",file);
NSArray *files =[fileManage subpathsAtPath:myDirectory];
NSLog(@"%@",files);
删除文件
[fileManager removeItemAtPath:flieName error:nil];