iOS

iOS 文件操作

2018-07-20  本文已影响8人  陵无山

沙盒机制

沙盒的概念

获取沙盒目录

NSString类路径处理方法和IO操作

NSData和I/O

NSData是用来包装数据的,NSData存储的是二进制数据屏蔽了数据之间的差异,文本、音频、图像等数据都可用NSData来存储。

NSData的写入与读取(I/O)

// NSData写入文件
// 创建一个存放NSData数据的路径
NSString *fileDataPath = [docPath stringByAppendingPathComponent:@"icon"];

// 得到一个UIImage对象
UIImage *image = [UIImage imageNamed:@"icon.jpg"];

// 将UIImage对象转换成NSData对象
NSData *data = UIImageJPEGRepresentation(image, 0);
[data writeToFile:fileDataPath atomically:YES];
NSLog(@"fileDataPath is %@", fileDataPath);

// 从文件读取存储的NSData数据
NSData *resultData = [NSData dataWithContentsOfFile:fileDataPath];
// 将得到的NSData数据转换成原有的图片对象
UIImage *resultImage = [UIImage imageWithData:resultData];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
imageView.image = resultImage;
[self.view addSubview:imageView];

NSString 与 NSData

UIImage 与 NSData

NSArray的写入与读取(I/O)

    NSString *filePath = [docPath stringByAppendingPathComponent:@"language.txt"];
    NSArray *array = @[@"C语言", @"JAVA",@"Objective-C", @"Swift", @"PHP", @"C++"];
    //数组写入文件
    [array writeToFile:filePath atomically:YES];
    NSArray *resultArr = [NSArray arrayWithContentsOfFile:filePath];
    NSLog(@"%@", resultArr[1]);

NSDictionary的写入与读取(I/O)

    NSString *filePath = [docPath stringByAppendingPathComponent:@"love,txt"];
    NSDictionary *dic = @{@"职业":@"程序员", @"梦想":@"代码无BUG"};
    //字典写入文件
    [dic writeToFile:filePath atomically:YES];
    NSDictionary *resultDic = [NSArray arrayWithContentsOfFile:filePath];
    NSLog(@"%@", resultDic[@"梦想"]);

文件管理

NSFileManager

NSFileHandle

+(NSFileHandle)fileHandleForReadingAtPath:path 打开一个文件用于读入
+(NSFileHandle
)fileHandleForWritingAtPath:path 打开一个文件用于写入
+(NSFileHandle)fileHandleForUpdatingAtPath:path 打开一个文件用于读写
-(NSData
)availableData 从设备或者通道返回可用数据
-(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 关闭文件

备注:

示例

#import <Foundation/Foundation.h>   
int main(int argc, const charchar * argv[])  
{  

    @autoreleasepool {  
        NSFileHandle *inFile,*outFile;  
        NSData *buffer;  
        NSString *fileContent = @"这些是文件内容,这些是文件内容,这些是文件内容,这些是文件内容,这些是文件内容";  
        NSFileManager *fm = [NSFileManager defaultManager];  

        //创建一个文件  
        [fm createFileAtPath:@"testFile.txt" contents:[fileContent dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];  
        //创建一个需要写入的文件  
        [fm createFileAtPath:@"outFile.txt" contents:nil attributes:nil];  

        //读取文件  
        inFile = [NSFileHandle fileHandleForReadingAtPath:@"testFile.txt"];  
        //写入文件  
        outFile = [NSFileHandle fileHandleForWritingAtPath:@"outFile.txt"];  

        if(inFile!=nil){  
            //读取文件内容  
            buffer = [inFile readDataToEndOfFile];  

            //将文件的字节设置为0,因为他可能包含数据  
            [outFile truncateFileAtOffset:0];  

            //将读取的内容内容写到outFile.txt中  
            [outFile writeData:buffer];  

            //关闭输出  
            [outFile closeFile];  

            //验证outFile内容  
            NSLog(@"%@",[NSString stringWithContentsOfFile:@"outFile.txt" encoding:NSUTF8StringEncoding error:NULL]);  


            //创建一个新的文件用来循环写入  
            [fm createFileAtPath:@"outFile2.txt" contents:nil attributes:nil];  

            //打开一个新的输出  
            outFile = [NSFileHandle fileHandleForWritingAtPath:@"outFile2.txt"];  

            //设置一个循环写入10条数据,每条数据都再后面添加上而不是覆盖  
            for (int i = 0; i<10; i++) {  
                //将偏移量设置为文件的末尾  
                [outFile seekToEndOfFile];  
                //写入数据  
                [outFile writeData:buffer];  
            }  

            //验证内容  
            NSLog(@"outFile2:%@",[NSString stringWithContentsOfFile:@"outFile2.txt" encoding:NSUTF8StringEncoding error:NULL]);  

            //关闭所有  
            [outFile closeFile];  
            [inFile closeFile];     
        }                   
    }  
    return 0;  
} 

复杂对象的读写(I/O)

记住

  • 复杂对象写入文件的过程(复杂对象->归档->NSData->writeToFile)
  • 从文件中读取出复杂对象过程(读取文件->NSData->反归档->复杂对象

实现

  1. 首先,复杂对象所属的类要遵守<NSCoding>

     @interface Person:NSObject**<NSCoding> **
           @property(nonatomic,copy) NSString *name 
           @property(nonatomic,assign) integer age; 
     @end
    
  2. 其次,实现协议中的两个方法:

      • (void)encodeWithCoder:(NSCoder *)aCoder; 序列化
      • (id)initWithCoder:(NSCoder *)aDecoder; 反序列化
// 对person对象进行归档时,此方法执行。
// 对person中想要进行归档的所有属性,进行序列化操作。
-(void)encodeWithCoder:(NSCoder *)aCoder
{
  [aCoder encodeObject:self.name forKey:@"name"];
  [aCoder encodeInteger:self.age forKey:@"age"];
}
// 对person对象进行反归档时,该方法执行。
// 创建一个新的person对象,所有属性都是通过反序列化得到的。
-(id)initWithCoder:(NSCoder *)aDecoder 
{
  self = [super init];
  if (self) {
    self.name = [aDecoder decodeObjectForKey:@"name"];
    self.age = [aDecoder decodeIntegerForKey:@"age"];
  }
  return self;
}
 
// 准备一个NSMutableData, 用于保存归档后的对象
NSMutableData *data = [NSMutableData data];
// 创建归档工具
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingMutableData:data];
// 归档
[archiver encodeObject:p] forKey:@"p1"];
// 结束
[archiver finishEncoding];
// 拼音写入沙盒路径
NSString *caches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [caches stringByAppendingPathComPonent:@"person"];
// 写入沙盒
[data writeToFile:filePath atomically:YES];
 
// 反归档
// 从filePath文件路径读取
NSData *data = [NSData dataWithContentsOfFile:filePath];
// 反归档工具
NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
// 反归档成对象
Person *p2 = [unArchiver decodeObjectForKey:@"p1"];
// 反归档结束
[unArchiver finshDeoding];

上一篇 下一篇

猜你喜欢

热点阅读