iOSノート-ファイルの書き込み、読み取り、操作

13639 ワード

プロジェクトでは、データを永続化して保存する必要がある場合があります.私たちのやり方の1つは、ファイルに書き込むことです.必要に応じてファイルから読み取ることができます.
//
//  main.m
//      
//
//  Created by hhg on 15/5/28.
//  Copyright (c) 2015  hhg. All rights reserved.
//

#import 

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        ///              
        NSString *stringPath = @"/Users/hhg/Desktop/string    .txt";
        NSString *dataPath   = @"/Users/hhg/Desktop/data    .txt";
        NSString *arrayPath  = @"/Users/hhg/Desktop/array    .plist";

        //   
        NSString *string = @"string   ";
        BOOL isWriteString =[string writeToFile:stringPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
        if (isWriteString) { NSLog(@"string       "); };

        NSData *data =[[NSData alloc]initWithContentsOfFile:stringPath];
        BOOL isWriteData =[data writeToFile:dataPath atomically:YES];
        if (isWriteData) { NSLog(@"data       "); }

        //                 NSString NSArray NSData NSNumber NSDictionary
        NSString *sanNameStr = @"  ";
        NSString *siNameStr = @"  ";
        NSString *wuNameStr = @"  ";
        NSArray *nameArray = [NSArray arrayWithObjects:sanNameStr, siNameStr, wuNameStr,nil];

        BOOL isWriteArray =[nameArray writeToFile:arrayPath atomically:YES];
        if (isWriteArray) { NSLog(@"array       "); }

        ///     
        NSString *readStr =[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"    string  : %@", readStr);

        NSString *readDataStr =[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"    data  :%@", readDataStr);

        NSArray *readArr =[[NSArray alloc]initWithContentsOfFile:arrayPath];
        NSLog(@"   array  :%@",readArr);

        //    plist  
        NSDictionary *dic =[[NSDictionary alloc]initWithObjectsAndKeys:
                            sanNameStr,@"  ",
                            siNameStr,@"  ",
                            wuNameStr,@"  ",
                            nameArray,@"    ", nil];

        [dic writeToFile:arrayPath atomically:YES];

        NSDictionary *myDic =[[NSDictionary alloc]initWithContentsOfFile:arrayPath];
        NSArray * nameArr =myDic[@"    "];
        NSLog(@"nameArr : %@",nameArr);
    }
    return 0;
}

正常にデータを書き終わった後、新しいデータを追加する必要があるので、上記のように再操作することはできません.再操作すると、元のデータが上書きされます.上書きを避けるためには、追加したデータのオフセット操作が必要です.
//
//  main.m
//      
//
//  Created by hhg on 15/4/29.
//  Copyright (c) 2015  hhg. All rights reserved.
//

#import 

int main(int argc, const char * argv[]) {
    @autoreleasepool
    {
        NSString *path = @"/Users/hhg/Desktop/      .txt";
        NSString*oldStr = @"old string ,";
        [oldStr writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];

        NSFileHandle *wirteFileHandle =[NSFileHandle fileHandleForWritingAtPath:path];

        //    
        NSString *appendString = @"append string";
        NSData *data =[appendString dataUsingEncoding:NSUTF8StringEncoding];

        //                               
        [wirteFileHandle seekToEndOfFile]; //            
        [wirteFileHandle writeData:data]; //    
        [wirteFileHandle closeFile]; //    

        //      
        //               
        NSFileHandle *readFileHandle =[NSFileHandle fileHandleForReadingAtPath:path];
        if (readFileHandle == nil) {
            NSLog(@"    ");
        }

        //        
        NSFileManager *fileManager =[NSFileManager defaultManager];
        NSDictionary *dic =[fileManager attributesOfItemAtPath:path error:nil];
        NSLog(@"dic : %@",dic);

        NSNumber *number =[dic objectForKey:NSFileSize];
        int  length = [number intValue];
        NSLog(@"length = %d", length);

        //          
        [readFileHandle seekToFileOffset:length/2];
        NSData *readData =[readFileHandle readDataToEndOfFile];//    
        //                
        // - (NSData *)readDataOfLength:(NSUInteger)length;

        NSString*readStr =[[NSString alloc]initWithData:readData encoding:NSUTF8StringEncoding];

        NSLog(@"readStr : %@",readStr);
        [readFileHandle closeFile];
    }
    return 0;
}

データの格納が完了すると、ビジネスのニーズに応じてデータの格納場所を変更する必要があります.ファイルの移動や削除などの操作が必要です.
//
//  main.m
//  NSFileManager
//
//  Created by hhg on 15/5/28.
//  Copyright (c) 2015  hhg. All rights reserved.
//

#import 

int main(int argc, const char * argv[]) {
    @autoreleasepool
    {
        //  NSFileManager            
        NSFileManager * file = [NSFileManager defaultManager];
        NSString *str = @"       ";
        //           
        NSData * data = [str dataUsingEncoding:NSUTF8StringEncoding];

        //            
        NSString *home = NSHomeDirectory();
        NSString *path = [home stringByAppendingPathComponent:@"file.txt"];
        [file createFileAtPath:path contents:data attributes:nil];
        NSLog(@"    = %@", home);

        /* ______________     _____________   */

        NSString *folderPath = @"/Users/hhg/Desktop/myFolder";
        BOOL isSuccess =[file createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
        if (isSuccess) {
            NSLog(@"       ");
        }

        /*___________    __________*/
        //       
        NSData *readData =[file contentsAtPath:path];
        //        
        NSString *readStr =[[NSString alloc]initWithData:readData encoding:NSUTF8StringEncoding];

        NSLog(@"       :  %@",readStr);
        /* __________         ______________   */
        //  
        NSString *movePath = @"/Users/hhg/Desktop/myFolder/file.txt";
        BOOL isMove = [file moveItemAtPath:path toPath:movePath error:nil];

        if (isMove) {
            NSLog(@"      ");
        }

        //    
        [file copyItemAtPath:movePath  toPath:folderPath error:nil];
        /* _________     ____________*/
        BOOL isDelete =  [file fileExistsAtPath:movePath];
        if ( isDelete ) {
//            [file removeItemAtPath:movePath  error:nil];
        }

        NSDictionary *dic = [file attributesOfItemAtPath:movePath error:nil];
        NSNumber *num = [dic objectForKey:NSFileSize];
        NSLog(@"  :%@", dic);
        NSLog(@"     :%@", num);
        //-->     ->    (     )->      ->      ->    

    }
    return 0;
}