【day0201_NSFileHandle】:文件句柄

1 NSFileHandle 文件对接器、文件句柄

常用API:

- (NSData *)readDataToEndOfFile;读取数据到最后

- (NSData *)readDataOfLength:(NSUInteger)length; 读取长度

- (void)writeData:(NSData *)data; 写数据

- (unsignedlonglong)seekToEndOfFile; 将文件指针移至最后,并返回文件长度

- (void)seekToFileOffset:(unsignedlonglong)offset; 指定文件指针位置

- (void)closeFile; 关闭文件,一般写完/读完数据要关闭文件

+ (id)fileHandleForReadingAtPath:(NSString *)path; 根据路径读取数据

+ (id)fileHandleForWritingAtPath:(NSString *)path; 根据路径写数据

案例代码:

/*

写入:NSString -> 文件

读取:文件 -> NSString

*/

- (void)viewDidLoad

{

[superviewDidLoad];

NSString *homePath = NSHomeDirectory();

NSLog(@"%@",homePath);

NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];

NSString *filePath = [documentsPath stringByAppendingPathComponent:@"hello.txt"];

NSString *fileContent = @"你好";

// 写入:

// 怎么把fileContent写到hello.txt呢

// 先把fileContent->NSData  ,  然后写到hello.txt中

// NSString -> NSData

NSData *data = [fileContent dataUsingEncoding:NSUTF8StringEncoding];

// NSData -> 文件完整步骤

// 准备空文件hello.txt

NSFileManager *fileManager = [NSFileManagerdefaultManager];

[fileManager createFileAtPath:filePath contents:nilattributes:nil];

// 创建文件对接器

NSFileHandle *fileHandle = [NSFileHandlefileHandleForWritingAtPath:filePath];

// 写入数据

[fileHandle writeData:data];

// 关闭文件对接器

[fileHandle closeFile];

// 写入文件还有更快捷的方法

//    [fileManager createFileAtPath:filePath contents:data attributes:nil];

// 读取

// 文件 -> NSData -> NSString

// 创建文件对接器

NSFileHandle *readHandle = [NSFileHandlefileHandleForReadingAtPath:filePath];

// 读数据

NSData *data1 = [readHandle readDataToEndOfFile];

// 关闭对接器

[readHandle closeFile];

// data -> string

NSString *str = [[NSStringalloc] initWithData:data1 encoding:NSUTF8StringEncoding];

NSLog(@"%@",str);

// string根据路径可以直接获取数据

NSString *str2 = [NSStringstringWithContentsOfFile:filePath encoding:NSUTF8StringEncodingerror:nil]; // 读取文件以UTF8显示

// 识别编码

NSStringEncoding encode;

NSString *str3 = [NSStringstringWithContentsOfFile:filePath usedEncoding:&encode error:nil]; // 该方法做了两件事,首先根据路径读取数据,然后把该数据的编码赋值给encode

NSLog(@"%d",encode); // 4 表示UTF8编码

}

【day0202_copyFileContent】:copy文件

练习:

先用NSString -> 文件

往Documents下写一个文件source.txt

文件的内容随便,有中文

需要写代码拷贝文件 -> copy .txt

源文件 -> NSData-> 新文件

FileHandle   NSData

- (void)viewDidLoad

{

[superviewDidLoad];

NSLog(@"%@",NSHomeDirectory());

NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDirectory, YES)[0];

NSString *filePath = [documentsPath stringByAppendingPathComponent:@"sourcefile.txt"];

NSData *data = [@"中文!"dataUsingEncoding:NSUTF8StringEncoding];

[[NSFileManagerdefaultManager] createFileAtPath:filePath contents:nilattributes:nil];

[[NSFileManagerdefaultManager] createFileAtPath:filePath contents:data attributes:nil];

// 文件 -> data

NSFileHandle *readHandle = [NSFileHandlefileHandleForReadingAtPath:filePath];

NSData *dataFromFile = [readHandle readDataToEndOfFile];

// data -> 新文件copy.txt

NSString *copyPath = [documentsPath stringByAppendingPathComponent:@"copy.txt"];

[[NSFileManagerdefaultManager] createFileAtPath:copyPath contents:dataFromFile attributes:nil];

// copy图片

NSData *picData = [NSDatadataWithContentsOfFile:@"/Users/.../01.jpg"];

NSString *picPath = [documentsPath stringByAppendingPathComponent:@"01.jpg"];

[[NSFileManagerdefaultManager] createFileAtPath:picPath contents:picData attributes:nil];

}

【day0203_merge合并文件】

合并一些文件的内容到新文件中

- (void)viewDidLoad

{

[superviewDidLoad];

NSLog(@"%@",NSHomeDirectory());

// 获取documents路径

NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];

// 源文件名数组

NSArray *sourceNames = @[@"a.txt", @"b.txt", @"c.txt",];

// 合并文件名

NSString *outputName = @"combine.txt";

// 合并文件路径

NSString *outputFilePath = [documents stringByAppendingPathComponent:outputName];

// 创建合并文件

[[NSFileManagerdefaultManager] createFileAtPath:outputFilePath contents:nilattributes:nil];

// 创建filehandle

NSFileHandle *writeHandle = [NSFileHandlefileHandleForWritingAtPath:outputFilePath];

// 循环写入数据

for (NSString *sourceName in sourceNames) {

NSString *sourceFilePath = [documents stringByAppendingPathComponent:sourceName]; // 源文件路径

NSFileHandle *readHandle = [NSFileHandlefileHandleForReadingAtPath:sourceFilePath]; // 创建读取handle

NSData *readData = [readHandle readDataToEndOfFile]; // 读出数据

[writeHandle writeData:readData]; // 写到新文件中

[readHandle closeFile]; // 关闭读取文件

}

// 关闭文件

[writeHandle closeFile];

}

【day0204_FilePointer文件指针】

文件指针的使用

按指定字节拷贝文件

- (void)viewDidLoad

{

[superviewDidLoad];

NSLog(@"%@",NSHomeDirectory());

NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];

NSString *sourcePath = [documentsPath stringByAppendingPathComponent:@"source.txt"];

// 按每次1000字节的中专拷贝一张图片

NSString *picPath = @"/Users/tarena/yz/第三阶段(UI核心_Model赵哲)/day02/1-4.jpg";

// 拷贝

// 创建读取handle

NSFileHandle *readHandle = [NSFileHandlefileHandleForReadingAtPath:picPath];

unsignedlonglong picSize = [readHandle seekToEndOfFile]; // 图片大小

unsignedlonglong offset = 0;

NSString *path = [documentsPath stringByAppendingPathComponent:@"0.jpg"]; // document下图片路径

[[NSFileManagerdefaultManager] createFileAtPath:path contents:nilattributes:nil]; // 创建空jpg文件

NSFileHandle *writeHandle = [NSFileHandlefileHandleForWritingAtPath:path]; // 创建写handle

[readHandle seekToFileOffset:0]; // 设置文件指针

// 循环读取文件写入到document下空的jpg文件

NSData *data = nil;

while (offset + 1000 <= picSize) { // 一次读1000

data = [readHandle readDataOfLength:1000];

[writeHandle writeData:data];

offset += 1000;

NSLog(@"%llu",offset);

}

// 不足1000的读到最后

data = [readHandle readDataToEndOfFile];

[writeHandle writeData:data];

[readHandle closeFile];

[writeHandle closeFile];

// 文件指针的使用

NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:sourcePath];

unsignedlonglong fileSize = [readHandle seekToEndOfFile]; // 该方法会把文件指针移至最后并返回文件大小

NSLog(@"%llu",fileSize);

[readHandle seekToFileOffset:0]; // 设置指针位置

NSData *data = [readHandle readDataOfLength:3]; // 读取长度以字节为单位一个汉子占3个字节

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

NSLog(@"%@",str);

[readHandle closeFile];

}

【day0205_文件查看器】

MXDocumentsViewController.m

- (void)viewDidLoad

{

[superviewDidLoad];

if (!self.path) {

self.path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];

}

NSArray *fileNameArray = [[NSFileManagerdefaultManager] contentsOfDirectoryAtPath:self.patherror:nil];

self.files = [NSMutableArrayarray];

for (NSString *fileName in fileNameArray) {

NSString *filePath = [self.pathstringByAppendingPathComponent:fileName];

[self.filesaddObject:filePath];

}

NSLog(@"%@",self.files);

// Uncomment the following line to preserve selection between presentations.

// self.clearsSelectionOnViewWillAppear = NO;

// Uncomment the following line to display an Edit button in the navigation bar for this view controller.

// self.navigationItem.rightBarButtonItem = self.editButtonItem;

}

- (void)didReceiveMemoryWarning

{

[superdidReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

returnself.files.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

staticNSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

// Configure the cell...

NSString *filePath = self.files[indexPath.row];

if ([[filePath pathExtension] isEqualToString:@"jpg"]) {

cell.textLabel.text = [filePath lastPathComponent];

cell.imageView.image = [UIImageimageWithContentsOfFile:filePath];

}elseif([[filePath pathExtension] isEqualToString:@"txt"]){

cell.textLabel.text = [filePath lastPathComponent];

}else{ //目录

cell.textLabel.text = [filePath lastPathComponent];

[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];

}

return cell;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

NSString *filePath = self.files[indexPath.row];

if ([[filePath pathExtension] isEqualToString:@"jpg"]) {

[selfperformSegueWithIdentifier:@"pictureVC"sender:filePath];

}elseif([[filePath pathExtension] isEqualToString:@"txt"]){

[selfperformSegueWithIdentifier:@"txtVC"sender:filePath];

}else{ //目录

MXDocumentsViewController *docvc = [self.storyboardinstantiateViewControllerWithIdentifier:@"fileListTV"];

docvc.path = filePath;

[self.navigationControllerpushViewController:docvc animated:YES];

}

}

#pragma mark - Navigation

// In a story board-based application, you will often want to do a little preparation before navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

{

if ([segue.identifierisEqualToString:@"pictureVC"]) {

MXPictureViewController *picvc = segue.destinationViewController;

picvc.path = sender;

}elseif ([segue.identifierisEqualToString:@"txtVC"]){

MXTxtViewController *txtvc = segue.destinationViewController;

txtvc.path = sender;

}

}

02-IOSCore - NSFileHandle、合并文件、文件指针、文件查看器的更多相关文章

  1. windows下将多个文件里面的内容合并成一个一个文件

    如题:例如有多个章节的小说,现在要把他们合并成一个txt文件. 利用windows自带cmd工具: 一.拷贝合并1.将你的txt文档按照顺序分别命名为01.txt 02.txt 03.txt……2.将 ...

  2. C# 合并及拆分PDF文件

    C# 合并及拆分PDF文件 有时我们可能会遇到下图这样一种情况 — 我们需要的资料或教程被分成了几部分存放在多个PDF文件中,不管是阅读还是保存都不是很方便,这时我们肯定想要把这些PDF文件合并为一个 ...

  3. C# 将多个office文件转换及合并为一个PDF文件

    PDF文件介绍 PDF(Portable Document Format )文件源于20世纪90年代初期,如今早已成为了一种最流行的的文件格式之一.因为PDF文件有很多优点: 支持跨平台和跨设备共享 ...

  4. C使用FILE指针文件操作

    文件的基本概念 所谓“文件”是指一组相关数据的有序集合. 这个数据集有一个名称,叫做文件名.实际上在前面的各章中我们已经多次使用了文件,例如源程序文件.目标文件.可执行文件.库文件 (头文件)等.文件 ...

  5. minify合并js和css文件

    压缩 JavaScript 和 CSS,是为减少文件大小,节省流量开销:合并 JavaScript 和 CSS,是为了减少请求数量,减轻服务器压力.而这些枯燥又没有技术含量的工作,我们以前通常会手动处 ...

  6. 使用ILmerge合并Exe、Dll文件的帮助类

    原文:使用ILmerge合并Exe.Dll文件的帮助类 using System; using System.Collections.Generic; using System.Text; using ...

  7. 使用grunt完成requirejs的合并压缩和js文件的版本控制

    最近有一个项目使用了 requirejs 来解决前端的模块化,但是随着页面和模块的越来越多,我发现我快要hold不住这些可爱的js文件了,具体表现在每个页面都要设置一堆 requirejs 的配置( ...

  8. 压缩网站的css和js,合并多个文件到一个文件

    压缩网站的css和js,合并多个文件到一个文件uglifyjs index.js html5shiv.min.js -o all.min.jsuglifycss index.min.css web.c ...

  9. Java+XSL合并多个XML文件

    使用 Java 解析 XML 文件有许多成熟的工具,如 dom4j 等等.但在一些场景中,我们可能使用 Ant.Maven 等构建工具对多个 XML 文件进行合并,我们希望可以直接通过脚本文件,或者简 ...

随机推荐

  1. Java thread中对异常的处理策略

    转载:http://shmilyaw-hotmail-com.iteye.com/blog/1881302 前言 想讨论这个话题有一段时间了.记得几年前的时候去面试,有人就问过我一个类似的问题.就是j ...

  2. WEB ICON 的探讨

    一般考虑到webicon 就是cssSprite和自定义font:本文基于下述而总结和进行分析,如有笔误有望指出,谢谢 在线教程:用字体在网页中画ICON图标 http://www.imooc.com ...

  3. 转: sublime text 2 前端编码神器-快捷键与使用技巧介绍

    代码编辑器或者文本编辑器,对于程序员来说,就像剑与战士一样,谁都想拥有一把可以随心驾驭且锋利无比的宝剑,而每一位程序员,同样会去追求最适合自己的强大.灵活的编辑器,相信你和我一样,都不会例外. 如果说 ...

  4. 设计模式总结1--observer pattern

    <!-- 设计模式 --><!--是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结.使用设计模式是为了可重用代码.让代码更容易被他人理解.保证代 码可靠性 --&g ...

  5. tomcat简介之web.xml详解(转)

    http://blog.csdn.net/facepp/archive/2008/04/19/2306602.aspx 位于每个Web应用的WEB-INF路径下的web.xml文件被称为配置描述符,这 ...

  6. wiki oi 3116 高精度练习之加法

    题目描述 Description 给出两个正整数A和B,计算A+B的值.保证A和B的位数不超过500位. 输入描述 Input Description 读入两个用空格隔开的正整数 输出描述 Outpu ...

  7. 物流追踪 - -GPS和GPRS应用

    源码1: #include<stdio.h> #include<stdlib.h> #include<string.h> #include<termios.h ...

  8. jbpm系列之五--使用decision节点判断分支情况

    我们在用JBPM做流程的时候,很多时候会遇到需要判断的节点.类似java中的switch,根据不同的状态,跳转到不同的节点. 首先我们定义一个流程信息,jpdl流程图如下 明显的可以看到,在此种情况下 ...

  9. list,map的疑问

    代码: package com.wyl; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator ...

  10. eclipse the user operation is waiting for building workspace" to complete

    "the user operation is waiting for building workspace" to complete", 解决办法: 1.选择菜单栏的“P ...