02-IOSCore - NSFileHandle、合并文件、文件指针、文件查看器
【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、合并文件、文件指针、文件查看器的更多相关文章
- windows下将多个文件里面的内容合并成一个一个文件
如题:例如有多个章节的小说,现在要把他们合并成一个txt文件. 利用windows自带cmd工具: 一.拷贝合并1.将你的txt文档按照顺序分别命名为01.txt 02.txt 03.txt……2.将 ...
- C# 合并及拆分PDF文件
C# 合并及拆分PDF文件 有时我们可能会遇到下图这样一种情况 — 我们需要的资料或教程被分成了几部分存放在多个PDF文件中,不管是阅读还是保存都不是很方便,这时我们肯定想要把这些PDF文件合并为一个 ...
- C# 将多个office文件转换及合并为一个PDF文件
PDF文件介绍 PDF(Portable Document Format )文件源于20世纪90年代初期,如今早已成为了一种最流行的的文件格式之一.因为PDF文件有很多优点: 支持跨平台和跨设备共享 ...
- C使用FILE指针文件操作
文件的基本概念 所谓“文件”是指一组相关数据的有序集合. 这个数据集有一个名称,叫做文件名.实际上在前面的各章中我们已经多次使用了文件,例如源程序文件.目标文件.可执行文件.库文件 (头文件)等.文件 ...
- minify合并js和css文件
压缩 JavaScript 和 CSS,是为减少文件大小,节省流量开销:合并 JavaScript 和 CSS,是为了减少请求数量,减轻服务器压力.而这些枯燥又没有技术含量的工作,我们以前通常会手动处 ...
- 使用ILmerge合并Exe、Dll文件的帮助类
原文:使用ILmerge合并Exe.Dll文件的帮助类 using System; using System.Collections.Generic; using System.Text; using ...
- 使用grunt完成requirejs的合并压缩和js文件的版本控制
最近有一个项目使用了 requirejs 来解决前端的模块化,但是随着页面和模块的越来越多,我发现我快要hold不住这些可爱的js文件了,具体表现在每个页面都要设置一堆 requirejs 的配置( ...
- 压缩网站的css和js,合并多个文件到一个文件
压缩网站的css和js,合并多个文件到一个文件uglifyjs index.js html5shiv.min.js -o all.min.jsuglifycss index.min.css web.c ...
- Java+XSL合并多个XML文件
使用 Java 解析 XML 文件有许多成熟的工具,如 dom4j 等等.但在一些场景中,我们可能使用 Ant.Maven 等构建工具对多个 XML 文件进行合并,我们希望可以直接通过脚本文件,或者简 ...
随机推荐
- U盘安装Win7系统教程
U盘安装系统教程: http://wiki.jd.com/knowledge/6699.html
- 无法编辑的word解密
打开文档后,将其另存为XML文件,然后用UltraEdit(或者EditPlus,下载华军里搜索一下就行了)这个编辑软件打开刚刚存储的 XLM文件,查找<w:documentProtection ...
- Redis初始化配置及增删改查
package com.calc.tools import redis.clients.jedis.JedisPool import redis.clients.jedis.Jedis import ...
- java数据结构与算法值优先级队列
一.优先级队列 什么是优先级队列:优先级队列是一种比栈和队列更加常用的一种数据结构.在优先级队列中,数据项按照关键字的值有序.数据项插入到队列中时,会按照顺序插入到合适的位置,用来保证队列的顺序. 生 ...
- BZOJ 1579: [Usaco2009 Feb]Revamping Trails 道路升级( 最短路 )
最短路...多加一维表示更新了多少条路 -------------------------------------------------------------------------------- ...
- OCP-1Z0-053-V13.02-712新题
Why does the number of blocks for the table remain the sale after the shrink operation? A.Because ...
- C、C++中“*”操作符和“后++”操作符的优先级
假设有如下的定义 char carr[] = {"test"}; char cp = carr; 那么表达式 *cp++; 的右值是什么呢? 这个表达式在数组遍历的程序中非常常见, ...
- C语言程序转换为Python语言
python语言是支持用c来它写模块的,其实现有的很多模块也是用c写的.这里我做个简单的介绍. 先决条件:1.在linux上编写,需要自己编译出python的动态连接库.也就是要有libpython2 ...
- 使用python操作RabbitMQ,Redis,Memcache,SQLAlchemy 其一
一.概念 1.Memcached Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态 ...
- Code 16K 码
Code 16K 码是一种多层.连续型.可变长度的条码符号,可以表示全ASCII字符集的128个字符及扩展ASCII字符.它采用UPC及Code128字符.一个16层的Code 16K符号,可以表示7 ...