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 文件进行合并,我们希望可以直接通过脚本文件,或者简 ...
随机推荐
- Sql Server Convert函数转换Datetime类型数据
0 Feb 22 2006 4:26PM CONVERT(CHAR(19), CURRENT_TIMESTAMP, 0) 1 02/22/06 CONVERT(CHAR(8), CURRENT_TIM ...
- WPF qq界面(转)
原文:http://blog.csdn.net/u013981858/article/details/49130885 刚开始学WPF,自己写了个小东西,说实话写的并不好,好多东西不懂只是用现在懂的东 ...
- javascript对象属性——数据属性和访问器属性
ECMA-262第五版在定义时,描述了属性property的各种特征,定义这些特性是为了实现javascript引擎用的,为了表示该特性是内部值,规范把它们放在了两对儿方括号中,例如[[Enumera ...
- C# 常用参数
主函数调用 public static void Fun_Param() { ; ; ChangeValue(x, y); //外部调用Ref函数,必须初始化变量 ChangeValue(ref x, ...
- C# Programming Study #2
readonly (C# Reference) readonly 关键字是可以在字段上使用的修饰符. 当字段声明包括 readonly 修饰符时,该声明引入的字段赋值只能作为声明的一部分出现,或者 ...
- 高级UNIX环境编程11 线程
<pthread.h> pthread_equal pthread_self(void) pthread_create() pthread_close() pthread_join() p ...
- MAC Eclipse 快捷键
MAC Eclipse 快捷键大全备忘: Command + O:显示大纲 Command + 1:快速修复 Command + D:删除当前行 Command + Option + ↓:复制当前行到 ...
- 【操作系统】:Main features of the X86-64
The combination of the new hardware supplied by Intel and AMD ,and the new versions of GCC targeting ...
- window.open 使用方法总结
[1.最基本的弹出窗口代码] <SCRIPT LANGUAGE="javascript"> <!-- window.open ('test.html') - ...
- 【转】Android数字证书
Android数字证书的作用是非常重要的.Android操作系统每一个应用程序的安装都需要经过这一数字证书的签名. Android手机操作系统作为一款比较流行的开源系统在手机领域占据着举足轻重的地位. ...