iOS疯狂详解之NSFileHandle

//  创建一个文件

- (void)addField

{

NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

NSString *fieldPath = [documentPath stringByAppendingPathComponent:@"student.txt"];

NSLog(@"%@",fieldPath);

NSString *txt = @"wanglong";

[txt writeToFile:fieldPath atomically:YES encoding:NSUTF8StringEncoding error:nil];

//  从路径中 读取文件 获取NSFileHandle对象

NSFileHandle *handle = [NSFileHandle fileHandleForUpdatingAtPath:fieldPath];

//  获取文件内容的 结束偏移量

unsigned long long endOffset = handle.seekToEndOfFile;

[handle seekToFileOffset:4];

//  获取当前的偏移量 初始偏移量为0

unsigned long long offset = handle.offsetInFile;

//  准备要写入的字符串

NSString *str = @"123";

NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

[handle writeData:data];

NSString *saveStr = [NSString stringWithContentsOfFile:fieldPath encoding:NSUTF8StringEncoding error:nil];

NSLog(@"%@",saveStr);

//  -------------------------------------------------------

//  覆盖数据

NSFileHandle * srcFile, * destFile; //  输入文件、输出文件

NSData * buffer;//  读取的缓冲数据

NSFileManager * manager = [NSFileManager defaultManager];

NSString * sourcePath = [documentPath stringByAppendingPathComponent:@"sourceFile.txt"];//  源文件路径

NSLog(@"%@",sourcePath);

[manager createFileAtPath:sourcePath contents:[@"Hello" dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];

NSString * destPath = [documentPath stringByAppendingPathComponent:@"destFile.txt"];//  输出文件路径

BOOL success = [manager createFileAtPath:destPath contents:[@"abcdef" dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];

if (!success) {

return;

}

srcFile = [NSFileHandle fileHandleForReadingAtPath:sourcePath];

if (!destFile) {

return;

}

destFile = [NSFileHandle fileHandleForWritingAtPath:destPath];

if (!destFile) {

return;

}

[destFile truncateFileAtOffset:0];//  将输出文件的长度设为0,(也就是将原来的文件清空)

buffer = [srcFile readDataToEndOfFile];//  读取数据

[destFile writeData:buffer];

[srcFile closeFile];

[destFile closeFile];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 一、iOS中的沙盒机制 iOS应用程序只能对自己创建的文件系统读取文件,这个独立、封闭、安全的空间,叫做沙盒。它一...
    1d5cb7cff98d阅读 5,732评论 0 0
  • 一、iOS中的沙盒机制 iOS应用程序只能对自己创建的文件系统读取文件,这个独立、封闭、安全的空间,叫做沙盒。它一...
    tzhtodd阅读 5,059评论 0 2
  • iOS开发-文件管理(一) 一、iOS中的沙盒机制 iOS应用程序只能对自己创建的文件系统读取文件,这个独立、封闭...
    MacShare阅读 5,759评论 0 6
  • iOS开发系列--网络开发 概览 大部分应用程序都或多或少会牵扯到网络开发,例如说新浪微博、微信等,这些应用本身可...
    lichengjin阅读 9,228评论 2 7
  • /**ios常见的几种加密方法: 普通的加密方法是讲密码进行加密后保存到用户偏好设置( [NSUserDefaul...
    彬至睢阳阅读 8,213评论 0 7

友情链接更多精彩内容