IOS读取文件类和常用方法_IOS开发教程-查字典教程网
IOS读取文件类和常用方法
IOS读取文件类和常用方法
发布时间:2015-06-05 来源:查字典编辑
摘要:第一、NSFileHandleNSFileManager类主要对文件的操作(删除、修改、移动、复制等)NSFileHandle类主要对文件的...

第一、NSFileHandle

NSFileManager类主要对文件的操作(删除、修改、移动、复制等)

NSFileHandle类主要对文件的内容进行读取和写入

第二、NSFileHandle类处理文件的步骤

创建一个NSFileHandle对象

对打开的文件进行I/0操作

关闭文件

可以使用NSFileHandle进行断点续传

第三、实现查找功能的代码:

NSString *homePath=NSHomeDirectory();

NSString *filePath=[homePath stringByAppendingPathComponent:@"Desktop/hello.rtf"];

NSFileHandle *fileHandle=[NSFileHandle fileHandleForReadingAtPath:filePath];

NSUInteger length=[fileHandle availableData].length;

[fileHandle seekToFileOffset:length/2];

NSData *data=[fileHandle readDataToEndOfFile];

NSString *str=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSLog(@"%@",str);

第四、实现追加文件代码:

NSString *homePath=NSHomeDirectory();

NSString *filePath=[homePath stringByAppendingPathComponent:@"Desktop/hello.rtf"];

NSFileHandle *fileHandle=[NSFileHandle fileHandleForUpdatingAtPath:filePath];

//[fileHandle seekToEndOfFile];

[fileHandle seekToFileOffset:10];

NSString *str=@"data";

NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding];

[fileHandle writeData:data];

[fileHandle closeFile];

// insert code here...

NSLog(@"Hello, World!");

第五、实现复制文件的代码:

NSString *homePath=NSHomeDirectory();

NSString *filePath=[homePath stringByAppendingPathComponent:@"Desktop/hello.rtf"];

NSString *objPath=[homePath stringByAppendingPathComponent:@"Desktop/copy.rtf"];

NSFileManager *fileManager=[NSFileManager defaultManager];

BOOL success=[fileManager createFileAtPath:objPath contents:nil attributes:nil];

NSFileHandle *writeFile=[NSFileHandle fileHandleForReadingAtPath:filePath];

NSFileHandle *objFile=[NSFileHandle fileHandleForWritingAtPath:objPath];

[objFile readDataToEndOfFile];

NSData *data=[writeFile readDataToEndOfFile];

[objFile writeData:data];

[writeFile closeFile];

[objFile closeFile];

相关阅读
推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
  • 大家都在看
  • 小编推荐
  • 猜你喜欢
  • 最新IOS开发学习
    热门IOS开发学习
    编程开发子分类