15.文件管理一

1.概述

  1. NSFileManager类主要是对文件的操作(删除, 修改, 移动, 复制等)
  2. NSFileHandle类主要是对文件内容进行读取和写入操作, 步骤为:
    1) 创建一个NSFileHandle对象
    2) 对打开的文件进行I/O操作
    3)关闭文件按
  3. 可以使用NSFileHandle做文件的断点续传
  4. NSFileHandle只能读写文件, 不能创建文件, 创建文件使用NSFileManager.

2.NSFileHandle常用的方法

+ (instancetype)fileHandleForReadingAtPath:(NSString *)path;//打开一个文件准备读取
+ (instancetype)fileHandleForWritingAtPath:(NSString *)path;//打开一个文件准备写入
+ (instancetype)fileHandleForUpdatingAtPath:(NSString *)path;//打开一个文件准备更新
@property(readonly, copy)NSData *availableData;//从设备或通道返回可用数据

- (NSData *)readDataToEndOfFile;//从当前节点读取到文件末尾
- (NSData *)readDataOfLength:(NSUInteger)length;//从当前节点开始读取指定的长度数据
- (void)writeData:(NSData *)data;//写入数据

@property (readonly)unsigned long long offsetInFile;//获取当前文件的偏移量
- (unsigned long long)seekToEndOfFile;//跳到文件末尾
- (void)seekToFileOffset:(unsigned long long)offset;//跳到指定文件的偏移量
- (void)closeFile;//关闭文件

3.简单运用

/**1.追加数据****/
NSString *homePath = NSHomeDirectory();
NSString *filePath = [homePath stringByAppendingPathComponent:@"phone/cellPhone.text"];
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
//追加数据
[fileHandle seekToEndOfFile];
NSString *str = @"追加的数据";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
[fileHandle writeData:data];
[fileHandle closeFile];
/**2.定位读取数据**/
NSString *homePath = NSHomeDirectory();
NSString *filePath = [homePath stringByAppendingPathComponent:@"phone/cellPhone.text"];
NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];
NSUInteger length = [fileHandle availableData].length;
[fileHandle seekToFileOffset:length/2];
NSData *data = [fileHandle readDataToEndOfFile];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"
//***3.复制文件***
NSString *homePath = NSHomeDirectory();
NSString *filePath = [homePath stringByAppendingPathComponent:@"phone/cellPhone.text"];
NSString *tagetPath = [homePath stringByAppendingPathComponent:@"cellPhone_bak.text"];

NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success = [fileManager createFileAtPath:tagetPath contents:nil attributes:nil];
if (success) {
    NSLog(@"create success");
}

NSFileHandle *outFileHandle = [NSFileHandle fileHandleForWritingAtPath:tagetPath];
NSFileHandle *inFileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];

//[inFileHandle availableData];
NSData *data = [inFileHandle readDataToEndOfFile];
[outFileHandle writeData:data];

[outFileHandle closeFile];
[inFileHandle closeFile];

4.实例一

创建一个Dage.text文件, 获取当前的日期, 将日期格式为”2015/08/02 03: 20:00” 的形式. 然后一秒钟记录一次, 将新的时间存入到文件中.
WriteDate.h和WriteDate.m文件

#import <Foundation/Foundation.h>
@interface WriteDate : NSObject
- (void)runWrite;
@end
#import "WriteDate.h"
@implementation WriteDate

- (void)runWrite {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *path = NSHomeDirectory();
    NSString *filePath = [path stringByAppendingPathComponent:@"Date.text"];
    //创建文件
    BOOL success = [fileManager createFileAtPath:filePath contents:nil attributes:nil];
    if (success) {
        NSLog(@"create success");
    }
    //写文件对象
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:fileHandle repeats:YES];
}

- (void)timerAction:(NSTimer *)timer
{
    static int n = 0;
    NSFileHandle *fileHandle = timer.userInfo;
    //跳到文件的末尾
    [fileHandle seekToEndOfFile];

    NSDate *nowDate = [NSDate date];
    NSDateFormatter *dateformate = [[NSDateFormatter alloc] init];
    //设置日期的格式
    [dateformate setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
    //将日期对象格式为字符串
    NSString *datestring = [dateformate stringFromDate:nowDate];
    [dateformate release];

    datestring = [datestring stringByAppendingString:@"\n"];
    NSData *data = [datestring dataUsingEncoding:NSUTF8StringEncoding];
    [fileHandle writeData:data];

    if (n == 10) {
        [timer invalidate];
        [fileHandle closeFile];//关闭文件
    }
    n++;
}
@end

main.m文件

WriteDate *writeDate = [[WriteDate alloc] init];
[writeDate runWrite];
[writeDate release];

5.实例二

复制一个大型文件, 为了节约内存, 每次只读取500个字节
main.m文件

NSString *homePath = NSHomeDirectory();
//要复制的源文件路径
NSString *srcPath = [homePath stringByAppendingPathComponent:@"youdao.pkg"];
//目标文件路径
NSString *tagetPath = [homePath stringByAppendingPathComponent:@"yd.pkg"];

NSFileManager *fileManager = [NSFileManager defaultManager];
//创建目标文件
BOOL success = [fileManager createFileAtPath:tagetPath contents:nil attributes:nil];
if (success) {
    NSLog(@"create success");
}
//读取文件对象
NSFileHandle *inFile = [NSFileHandle fileHandleForReadingAtPath:srcPath];
//写文件对象
NSFileHandle *outFile = [NSFileHandle fileHandleForWritingAtPath:tagetPath];

//获取文件的属性
NSDictionary *fileAttri = [fileManager attributesOfItemAtPath:srcPath error:nil];
//获取文件的大小
NSNumber *fileSizeNum = [fileAttri objectForKey:NSFileSize];

BOOL isEnd = YES;
NSInteger readSize = 0;     //已经读取的文件大小
NSInteger fileSize = [fileSizeNum longValue];   //文件的总大小
NSAutoreleasePool *pool = nil;
int n = 0;
NSLog(@"开始复制....");
while (isEnd) {
    if (n % 10 == 0) {
        [pool release];
        pool = [[NSAutoreleasePool alloc] init];
    }

    //计算剩下未读文件的大小
    NSInteger subLeng = fileSize - readSize;
    NSData *data = nil;
    //如果剩余文件大小小于5000,则将剩下的数据全都读完,并且不再循环读取了
    if (subLeng < 5000) {
        isEnd = NO; //跳出循环
        data = [inFile readDataToEndOfFile]; //读取剩下的数据
    } else {
        //读取5000个字节
        data = [inFile readDataOfLength:5000];
        //累加读取的大小
        readSize += 5000;
        [inFile seekToFileOffset:readSize];
    }

    //写入数据
    [outFile writeData:data];
    n++;
}
//关闭文件
[outFile closeFile];
NSLog(@"文件复制成功");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值