• Object-C-NSFileHandle


    NSFileHandle 类中得到方法可以很方便的对文件数据进行读写、追加,以及偏移量的操作。

    NSFileHandle 基本步骤:

    1、打开文件,获取一个NSFileHandle 对象

    2、对打开NSFileHandle的文件对象进行I/O操作

    3、关闭文件对象

    +(NSFileHandle *)fileHandleForReadingAtPath:path 打开一个文件用于读入

    +(NSFileHandle *)fileHandleForWritingAtPath:path打开一个文件用于写入

    +(NSFileHandle *)fileHandleForUpdatingAtPath:path 打开一个文件用于读写

    -(NSData *)readDataToEndOfFile读取其余的数据直到文件的末尾(最多UINT_MAX字节)

    -(NSData *)readDataOfLength:(NSUInteger)bytes从文件中读取指定字节的内容

    -(void)writeData:data 将data写入文件

    -(unsigned long long)offsetInFile 获取当前偏移量

    -(void)seekToFileOffset:offset 设置偏移量

    -(unsigned long long)seekToEndOfFile 将偏移量定位到文件的末尾

    -(void)truncateFileAtOffset:offset将文件的长度设置为offset字节

    -(void)closeFile关闭文件

    NSFileManager *fm=[NSFileManager defaultManager];
        NSString *outFilePath = @"outfile.txt";
        NSString *contentStr =@"这是使用NSFileManager创建的一个文件";
        if([fm createFileAtPath:outFilePath contents:[contentStr dataUsingEncoding:NSUTF8StringEncoding] attributes:nil])
        {
            NSLog(@"create success");
        }else{
            NSLog(@"create Fail");
        }
        NSString *infilePath=@"inFile.txt";
        if([fm createFileAtPath:infilePath contents:nil attributes:nil]){
            NSLog(@"create success!");
        }
        
        NSFileHandle *outHandle =[NSFileHandle fileHandleForReadingAtPath:outFilePath];
        NSFileHandle *inHandle=[NSFileHandle fileHandleForReadingAtPath:infilePath];
        if(outHandle==nil||inHandle==nil)
        {
            NSLog(@"请确认文件是否存在!");
        }else{
            NSData *data=[outHandle readDataToEndOfFile];
            //clear
            [inHandle truncateFileAtOffset:0];
            [inHandle writeData:data];
            [outHandle closeFile];
            [inHandle closeFile];
        }
        //文件追加内容
        NSString *infilePath=@"inFile.txt";
        NSFileHandle *updateHandle =[NSFileHandle fileHandleForUpdatingAtPath:infilePath];
        NSString *str=@"追加内容";
        //偏移量 刚开始的时候在开头
        [updateHandle seekToEndOfFile];
        [updateHandle writeData:[str dataUsingEncoding:NSUTF8StringEncoding]];
        [updateHandle closeFile];

  • 相关阅读:
    基于注解的 Spring MVC 简单入门
    Spring MVC入门
    Java集合总结之Collection整体框架
    关于getClass().getClassLoader()
    Java生成和操作Excel文件
    Spring 实现发送电子邮件的两种方法
    java mail(发送邮件--163邮箱)
    Write operations are not allowed in read-only mode 只读模式下(FlushMode.NEVER/MANUAL)写操作不
    配置文件Struts.xml 中type属性 redirect,redirectAction,chain的区别
    关于Hibernate在反向工程时无法选择Spring DAO Type的解决方法【更新版】
  • 原文地址:https://www.cnblogs.com/Opaser/p/4563736.html
Copyright © 2020-2023  润新知