// // ViewController.m // OC17使用文件 // // Created by Zoujie on 15/10/17. // Copyright ? 2015年 Zoujie. All rights reserved. // #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // NSFileManager类 提供文件系统对文件或者目录执行基本操作 // NSFileHandle 提供的方法打开文件并对文件执行多次读/写操作。 #pragma mark 基本的文件操作 [self fileMangerBasic]; #pragma mark 使用NSData类 [self useNSdata]; #pragma mark 使用目录 [self fileMangerPath]; #pragma mark 枚举目录中的内容 // [self enumerater]; #pragma mark 使用路径 NSPathUtilities.h [self directory]; #pragma mark 复制文件使用NSProcessInfo类 实现基本的复制工具 // [self ProcessInfo]; #pragma mark 基本的文件操作:NSFileHandle [self textNSFileHandle]; #pragma mark NSURL类 [self textNSURL]; #pragma mark NSBundle类 [self textNSBundle]; } -(void)fileMangerBasic { // 假定存在一个名为“”textfile“的文件 NSString *fName = @"textfile"; NSFileManager *fm; NSDictionary *attr; NSData *data; // 从文件中读取数据 data = [fm contentsAtPath:fName]; NSLog(@"%@",data); // 需要创建文件管理器的实例 fm = [NSFileManager defaultManager]; // 首先确定测试文件存在 if ([fm fileExistsAtPath:fName] == NO) { NSLog(@"File doesn‘y exist!"); } // 创建一个副本 if ([fm copyItemAtPath:fName toPath:@"newfile" error:NULL] == NO) { NSLog(@"File Copy failed!"); } // 测试两个文件是否一致 if ([fm contentsEqualAtPath:fName andPath:@"newfile"] == NO) { NSLog(@"File are Not Equal"); } // 重命名副本 if ((attr = [fm attributesOfItemAtPath:@"newfile2" error:NULL]) == nil) { NSLog(@"Couldn‘t get file attributes"); } // 获取 newfile2 的大小 if ((attr = [fm attributesOfItemAtPath:@"newfile2" error:NULL])== nil) { NSLog(@"Couldn‘t get file attributes"); } NSLog(@"File Size is %llu bytes",[[attr objectForKey:NSFileSize] unsignedLongLongValue]); // 最后删除原始文件 if ([fm removeItemAtPath:@"fName" error:NULL] == NO) { NSLog(@"file removal failed"); } NSLog(@"All operations were successful"); // 显示新创建的文件内容 ,将文件的内容读入到一个字符串对象 ,NSUTF8StringEncoding说明文件包含常规的UTF8 ASCII字符 NSLog(@"%@",[NSString stringWithContentsOfFile:@"newfile2" encoding:NSUTF8StringEncoding error:NULL]); } -(void)useNSdata { //NSData 数据临时读入,收集 // 32位应用程序,NSData组多可存储2GB数据,64位应用程序,最多可以存储8EB,即8亿GB的数据。 NSFileManager *fm; NSData *fileData; fm = [NSFileManager defaultManager]; // 读取文件 newfile2 fileData = [fm contentsAtPath:@"newfile2"];//仅仅接受一个路径名,并将指定文件的内容读入该方法创建的存储区 if (fileData == nil) { NSLog(@"File read failed"); } // 将数据写入newfile3 if([fm createFileAtPath:@"newfile3" contents:fileData attributes:nil] == NO) { NSLog(@"Couldn‘t create the copy"); return; } NSLog(@"File copy was successful"); } -(void)fileMangerPath { NSString *dirName = @"testdir"; NSString *path; NSFileManager *fm; // 需要创建文件管理器的实例 fm = [NSFileManager defaultManager]; // 获取当前目录 path = [fm currentDirectoryPath]; NSLog(@"Current directory path is %@",path);// 路径"/"说明应用的根目录实在运行他得沙盒中,并不是整个iOS设备文件目录的根 // 创建一个新目录 if ([fm createDirectoryAtPath:dirName withIntermediateDirectories:YES attributes:nil error:NULL] == NO) { NSLog(@"Couldn‘t create directory"); } // 重命名新的目录 if ([fm moveItemAtPath:dirName toPath:@"newdir" error:NULL] == NO) { NSLog(@"Directory rename failed"); } // 更改目录到新的目录 if ([fm changeCurrentDirectoryPath:@"newdir"] == NO) { NSLog(@"Change directory failed"); } // 获取并显示当前的工作目录 path = [fm currentDirectoryPath]; NSLog(@"Current directory path os %@",path); NSLog(@"All operation were successful"); } -(void)enumerater { NSString *path; NSFileManager *fm; NSDirectoryEnumerator *dirEnum; NSArray *dirArray; // 需要创建文件管理器的实例 fm = [NSFileManager defaultManager]; // 获取当前工作目录的路径 path = [fm currentDirectoryPath]; // 枚举目录 dirEnum = [fm enumeratorAtPath:path]; NSLog(@"Contents of %@",path); while ((path = [dirEnum nextObject]) != nil) { NSLog(@"%@",path); } // 另一种枚举目录的方法 dirArray = [fm contentsOfDirectoryAtPath:[fm currentDirectoryPath] error:NULL]; NSLog(@"Contents using contentsOfDirectoryAtPath:error:"); for (path in dirArray) { NSLog(@"%@",path); } } -(void)directory { NSLog(@"**************一些路径的基本操作***********"); NSString *fName = @"path.m"; NSFileManager *fm ; NSString *path,*tempdir,*extension,*homedir,*fullpath; NSArray *components; fm = [NSFileManager defaultManager]; // 获取临时的工作目录 tempdir = NSTemporaryDirectory(); NSLog(@"Temporary Directory is %@",tempdir); // 从当前目录中提取基本目录 path = [fm currentDirectoryPath]; NSLog(@"Base dir is %@",[path lastPathComponent]); // 创建文件fName 在当前目录中得完整路径 fullpath = [path stringByAppendingPathComponent:fName]; NSLog(@"fullpath to %@ is %@",fName,fullpath); // 获取文件扩展名 extension = [fullpath pathExtension]; NSLog(@"extension for is %@ is %@",fullpath,extension); // 获取用户的主目录 homedir = NSHomeDirectory(); NSLog(@"Your home directory is : %@",homedir); // 拆分路径为各组成部分 components = [homedir pathComponents]; for (path in components) NSLog(@"%@",path); NSString *str = [self saveFilePath]; NSLog(@"%@",str); } //查找系统的特殊目录 如Applicatioin 和Documents 目录 -(NSString *) saveFilePath { NSArray *dirList = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *docDir = dirList[0]; return [docDir stringByAppendingPathComponent:@"saveFile"]; } -(void)ProcessInfo { // 使用命令行工具实现简单地文件复制 // copy from-file to-file [NSProcessInfo processInfo];//返回当前进程的信息 NSProcessInfo *info = [[NSProcessInfo alloc]init]; NSLog(@"%@",[info processName]);//正在执行的进程名称 NSFileManager *fm; NSString *source,*dest; BOOL isDir; NSProcessInfo *proc = [NSProcessInfo processInfo]; NSArray *args = [proc arguments];//返回当前进程的参数 fm = [NSFileManager defaultManager]; // 检查命令行中得两个参数 if ([args count] != 3) { NSLog(@"Usage: %@ src dest",[proc processName]); } source = args[0]; dest = args[1]; // 确定能够读取源文件 if ([fm isReadableFileAtPath:source] == NO) { NSLog(@"Can‘t read %@",source); } // 目标文件是否是一个目录 // 若是,添加源到目标的结尾 [fm fileExistsAtPath:dest isDirectory:&isDir]; if (isDir == YES) { dest = [dest stringByAppendingPathComponent:[source lastPathComponent]]; } // 若目标文件已存在,则删除文件 [fm removeItemAtPath:dest error:NULL]; // 执行复制 if([fm copyItemAtPath:source toPath:dest error:NULL] == NO) { NSLog(@"Copy failed!"); return; } } -(void)textNSFileHandle { //假设存在一个"textFile"文件 NSFileHandle *inFile,*outFile; NSData *buffer; // 打开文件textfile 并读取 inFile = [NSFileHandle fileHandleForReadingAtPath:@"textfile"]; if (inFile == nil) { NSLog(@"Open of textfile for reading failed"); } // 如果需要,首先创建输出文件 [[NSFileManager defaultManager] createFileAtPath:@"textout" contents:nil attributes:nil]; // 打开outfile文件进行写入 outFile = [NSFileHandle fileHandleForWritingAtPath:@"textout"]; if (outFile == nil) { NSLog(@"Open of textout for writing failed"); } // 因为它可能包含数据截断输出文件 [outFile truncateFileAtOffset:0]; // 从infile 中读取数据,将它写到outFile buffer = [inFile readDataToEndOfFile]; [outFile writeData:buffer]; // 关闭这两个文件 [inFile closeFile]; [outFile closeFile]; // 验证文件的内容 NSLog(@"%@",[NSString stringWithContentsOfFile:@"textout" encoding:NSUTF8StringEncoding error:NULL]); // 追加文件"fileA" 到“fielB”的末尾 [self add]; } -(void)add { NSFileHandle *inFile,*outFile; NSData *buffer; // 打开文件fileA进行读取 inFile = [NSFileHandle fileHandleForReadingAtPath:@"fileA"]; if (inFile == nil) { NSLog(@"Open of fileA for reading failed"); } // 打开文件fileB进行更新 outFile = [NSFileHandle fileHandleForWritingAtPath:@"fileB"]; if (outFile == nil) { NSLog(@"Open of fileB for writing failed"); } // 在outFile的末尾进行查找 [outFile seekToEndOfFile]; // 从inFile 中读取数据,将它写到outFile buffer = [inFile readDataToEndOfFile]; [outFile writeData:buffer]; // 关闭两个文件 [inFile closeFile]; [outFile closeFile]; // 验证它的内容 NSLog(@"%@",[NSString stringWithContentsOfFile:@"fileB" encoding:NSUTF8StringEncoding error:NULL]); } -(void)textNSURL { NSURL *myURL = [NSURL URLWithString:@"http://classroomM.com"]; NSString *myHomePage = [NSString stringWithContentsOfURL:myURL encoding:NSASCIIStringEncoding error:NULL]; NSLog(@"%@",myHomePage); } -(void)textNSBundle { NSString *txtFilePath = [[NSBundle mainBundle]pathForResource:@"instructions" ofType:@"txt"];//返回文件路径,随后就可以读取文件的内容到程序中 //比如,本地化字符串,不同语言的文字 NSString *instructions = [NSString stringWithContentsOfFile:txtFilePath encoding:NSUTF8StringEncoding error:NULL]; // 列出应用包中图片目录中以jpg为文件后缀的图片 NSArray *birds = [[NSBundle mainBundle] pathsForResourcesOfType:@"jpg" inDirectory:@"birdImages"]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
原文:http://my.oschina.net/u/2319073/blog/519114