OC中文件读取类(NSFileHandle)介绍和常用使用方法

# NSFileHandle

## 1.NSFileManager类主要对于文件的操作(删除,修改,移动,赋值等等)

```objc
//判断是否有 tagetPath 文件路径,没有就创建

NSFileManager *fileManage = [NSFileManager defaultManager];

BOOL success = [fileManage createFileAtPath:tagetPath contents:nil attributes:nil];

if (success) {

NSLog(@"create success");

}
```

## 2.NSFileHandle类主要对文件的内容进行读取和写入操作

### ①NSFileHandle处理文件的步骤

#### 1:创建一个NSFileHandle对象

```objc
//创建流
NSFileHandle *inFileHandle = [NSFileHandle fileHandleForReadingAtPath:srcPath];

NSFileHandle *outFileHandle = [NSFileHandle fileHandleForWritingAtPath:tagetPath];
```

#### 2:对打开的文件进行I/O操作

```objc
//获取文件路径
NSString *homePath = NSHomeDirectory();

NSString *filePath = [homePath stringByAppendingPathComponent:@"phone/Date.text"];

NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];

 //定位到最后
 [fileHandle seekToEndOfFile];

 //定位到某个位置,100字节之后
[fileHandle seekToFileOffset:100];

//追加的数据
NSString *str = @"add world";

NSData *stringData = [str dataUsingEncoding:NSUTF8StringEncoding];

//追加写入数据
[fileHandle writeData:stringData];
```

#### 3:关闭文件对象操作

```objc
  //关闭流
[fileHandle closeFile];
```


##### 常用处理方法,读

```objc
//读取文件内容
void readByFile(){

//文件路径
NSString *homePath = NSHomeDirectory();

NSString *filePath = [homePath stringByAppendingPathComponent:@"phone/cellPhone.text"];
NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];
NSInteger length = [fileHandle availableData].length;

//跳转到指定位置
[fileHandle seekToFileOffset:length/2];
NSData *data = [fileHandle readDataToEndOfFile];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);

[fileHandle closeFile];

}

```

##### 复制文件

```objc
void copy2Other(){
NSString *homePath = NSHomeDirectory();
NSString *filePath = [homePath stringByAppendingPathComponent:@"phone/cellPhone.text"];
NSString *tagetPath = [homePath stringByAppendingPathComponent:@"phone/cellPhone_bak.text"];

//是否有这个文件,没有则创建
NSFileManager *fileManage =[NSFileManager defaultManager];
BOOL success = [fileManage createFileAtPath:tagetPath contents:nil attributes:nil];
if (success) {
NSLog(@"create success");
}

//通过 NSFileHandle 读取源文件,写入另一文件中
NSFileHandle *outFileHandle = [NSFileHandle fileHandleForWritingAtPath:tagetPath];
NSFileHandle *inFileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];
NSData *data = [inFileHandle readDataToEndOfFile];
[outFileHandle writeData:data];

//关闭流
[inFileHandle closeFile];
[outFileHandle closeFile];
}

原文地址:https://www.cnblogs.com/ShaoYinling/p/4579119.html