10.4 NSFileHandle


#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

#if 0
    NSFileManager *fileManager = [NSFileManager defaultManager];  
   
    //后缀为txt并不一定就是文本文件,还是得看文件类型。
    NSString *path = @"~/desktop/demoFile.txt";
    //把@""字符串写到path里
    [fileManager createFileAtPath:path contents:[@"hello world hellelellelelelelelelelele" dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
    
    /*
    NSError *error;
    [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
    NSLog(@"errro:%@",error);
    */
    
    BOOL isFileExi = [fileManager fileExistsAtPath:path isDirectory:nil];
    //文件的属性放到字典里
    NSDictionary *attris = [fileManager attributesOfItemAtPath:path error:nil];
    //打印属性
    NSLog(@"attris = %@",attris);
    //打印文件大小
    NSLog(@"fileSize = %@",attris[NSFileSize]);
    //打印data的长度
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSLog(@"%ld",data.length);
    
#endif
    
    NSString *path = @"~/desktop/demoFile.txt";
    //NSFileHandle像一个通道,使用完了记得关闭
    //读取文件
    NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:path];
    //写入文件
    NSFileHandle *writeHandle = [NSFileHandle fileHandleForWritingAtPath:path];
    
//    NSData *data = [readHandle readDataToEndOfFile];
    NSData *data = [readHandle readDataOfLength:5];
    //每次读5个字节
    data = [readHandle readDataOfLength:5];
    NSLog(@"-->readhandle:%@",[[NSString alloc]initWithData:dataencoding:NSUTF8StringEncoding]);

    //    [writeHandle truncateFileAtOffset:1024*1024*2];
    
//    [writeHandle seekToEndOfFile];
    //从第三个字节开始往后写
    [writeHandle seekToFileOffset:3];
    
    //把"***"写入到文件里
    [writeHandle writeData:[@"***" dataUsingEncoding:NSUTF8StringEncoding]];
    //把"---"写入到文件
    [writeHandle writeData:[@"---" dataUsingEncoding:NSUTF8StringEncoding]];
    //关闭readHandle
    [readHandle closeFile];
    //关闭writeHandle
    [writeHandle closeFile];
    
}

//写一个复制文件1到文件2的方法,思路如下:
- (void)copyFile:(NSString*)source to:(NSString*)target{
    //创建一个目标文件
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager createFileAtPath:target contents:nil attributes:nil];

    //拿到源文件的属性,文件大小
    NSDictionary *tempDict = [fileManager attributesOfItemAtPath:source error:nil];

    NSNumber *tmpNum = tempDict[NSFileSize];

    NSUInteger filelength = tmpNum.unsignedIntegerValue;

    //次数为:字节长度/5
    NSInteger count = filelength / 5;
    
    //打开读写通道
    NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:source];

    NSFileHandle *writeHandle = [NSFileHandle fileHandleForWritingAtPath:target];

    //用for循环写,每次读取5个字节,写入tempData
    for (NSInteger i = 0; i

你可能感兴趣的:(10.4 NSFileHandle)