• NSFileHandle(文件对接器)


     1 #import "ViewController.h"
     2 
     3 @interface ViewController ()
     4 
     5 @end
     6 
     7 @implementation ViewController
     8 
     9 - (void)viewDidLoad {
    10     [super viewDidLoad];
    11    //由于文件对接器不能创建文件,所以必须借助文件管理器创建文件,
    12     NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    13     
    14     NSString *filePath = [documents stringByAppendingPathComponent:@"text.txt"];
    15     NSString *str = @"123456789abcdedfghij";
    16     [str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    17     NSLog(@"%@",filePath);
    18     
    19     //文件对接器,对文件内容进行操作
    20     
    21     //读取
    22     NSFileHandle *readFileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];
    23     //从文件中得到可用数据
    24     //NSData *availableData = [readFileHandle availableData];
    25     //NSLog(@"%@",[[NSString alloc] initWithData:availableData encoding:NSUTF8StringEncoding]);
    26     
    27     //从当前节点,读取指定长度的数据,须把前边的availbleData注掉,不然取不到
    28     NSData *lengthData = [readFileHandle readDataOfLength:10];
    29     NSLog(@"%@",[[NSString alloc] initWithData:lengthData encoding:NSUTF8StringEncoding]);
    30     
    31     //设置节点偏移量
    32     [readFileHandle seekToFileOffset:0];
    33     NSData *lengthData2 = [readFileHandle readDataOfLength:5];
    34     NSLog(@"%@",[[NSString alloc] initWithData:lengthData2 encoding:NSUTF8StringEncoding]);
    35     
    36     NSData *lengthData3 = [readFileHandle readDataOfLength:5];
    37     NSLog(@"%@",[[NSString alloc] initWithData:lengthData3 encoding:NSUTF8StringEncoding]);
    38     //从当前节点读取到文件末尾
    39     NSData *endData = [readFileHandle readDataToEndOfFile];
    40     NSLog(@"%@",[[NSString alloc] initWithData:endData encoding:NSUTF8StringEncoding]);
    41     
    42     //关闭文件
    43     [readFileHandle closeFile];
    44     //写入数据
    45     NSFileHandle *writeHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
    46     
    47     //设置节点位置
    48     [writeHandle  seekToFileOffset:10];
    49     //写入
    50     [writeHandle writeData:lengthData];
    51     //获取节点偏移量
    52     NSInteger offset = [writeHandle offsetInFile];
    53     NSLog(@"%ld",offset);
    54     
    55     //将文件长度设置为偏移量
    56     [writeHandle truncateFileAtOffset:40];
    57     //关闭文件
    58     [writeHandle closeFile];
    59     
    60     
    61 }
  • 相关阅读:
    .Net操作Sharepoint常用方法(1) 判断List或Library是否存在
    Aspose.Cells读取Excel获取DataTable方法
    Nginx系统学习笔记(1)Say Hello
    老刘Hadoop学习笔记(6)Hadoop 单机模式 伪分布式 完全分布式区别
    老刘Hadoop学习笔记(5)安装JDK
    老刘Hadoop学习笔记(4)JDK和Open JDK区别
    老刘Hadoop学习笔记(3)新建用户及用户组
    老刘Hadoop学习笔记(2)修改虚拟机hostname及hosts文件
    老刘Hadoop学习笔记(1)开始学习
    MySQL中变量为空时不执行where过滤
  • 原文地址:https://www.cnblogs.com/DevinSMR/p/5263692.html
Copyright © 2020-2023  润新知