NSFileHandle的使用方法---iOS上的归档(增加更改内容的方法).

上一章我们介绍了在iOS上的归档以及解档, 今天我们在归档之后稍微做一些改变, 使得解档之后得到的结果有所不同, 这个方法类似NSMutableXXX, 可修改里面的参数, 下面让我们来看看吧.

涉及的方法:

seekToFileOffset:这个方法是寻求方法的偏移, 意思就是在文件中寻找文本里的起点.

readDataOfLength:这个方法是指读取文件的长度是多少.

offsetInFile:是指写到第几个位置.

#import "ViewController.h"
#define PZ NSLog(@"----我是一条华丽的分割线----");

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/test.txt"];
//    NSLog(@"%@", path);
    //1.创建文件
    [[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil];
    NSString *str = @"Hello, world!";
    PZ;
    
    //2.只写的方式打开文件, feleHandleForWritingAtPath是返回一个只写的方法.
    NSFileHandle *writeHanle = [NSFileHandle fileHandleForWritingAtPath:path];
    //把str里的字符串以UTF8编码存入data.
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    //把data里的东西存入writeHandle
    [writeHanle writeData:data];
    //再一次添加, 会直接加到前一个字符串的后面.
    [writeHanle writeData:data];
    PZ;

    //seekToFileOffset:0 是指跳到文件开头.
    [writeHanle seekToFileOffset:0];
    //把字符串@"xxx"以UTF8编码写入writeHanle文件中.
    [writeHanle writeData:[@"xxx" dataUsingEncoding:NSUTF8StringEncoding]];
    //offsetInFile是指写到第几个位置.
    NSLog(@"%llu", writeHanle.offsetInFile);

    PZ;
    //4.关闭文件
    [writeHanle closeFile];
    PZ;
    //使用fileURLWithpath读取path的路径.
    NSURL *url = [NSURL fileURLWithPath:path];
    //再把url里面的传给readHandle.
    NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingFromURL:url error:nil];
    
    //offsetInFile是指写到第几个位置.
    NSLog(@"%llu -----", readHandle.offsetInFile);
    //seekToFileOffset:是指定文件的偏移量.
    [readHandle seekToFileOffset:0];
    
    //readDataOfLength:的意思就是阅读readHandle文档中10的长度内容.
    NSData *data1 = [readHandle readDataOfLength:10];
    //把二进制文件data1以UTF8编码存入NSString对象str2中.
    NSString *str2 = [[NSString alloc]initWithData:data1 encoding:NSUTF8StringEncoding];
    //关闭文件
    NSLog(@"%@", str2);
    [readHandle closeFile];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

输出的结果:

2014-10-19 19:41:58.407 FileHandleDemo[13118:714260] 3
2014-10-19 19:41:58.407 FileHandleDemo[13118:714260] 0 -----
2014-10-19 19:41:58.407 FileHandleDemo[13118:714260] xxxlo, wor
原文地址:https://www.cnblogs.com/iOSCain/p/4035359.html