ios文件存儲--NSFileHandle

一、內容追加
首先在根目錄創建一個名爲filehandletest.txt的文件,然後往裏面追加內容:代碼如下

NSString *homePath = NSHomeDirectory();
        NSString *filePath = [homePath stringByAppendingPathComponent:@"filehandletest.txt"];
        NSFileHandle *handle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];//創建一個更新內容的handle
        [handle seekToEndOfFile];//指定到文件的末尾
        NSString *str = @"filehandletest";//追加的內容
        NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
        [handle writeData:data];//寫入數據
        [handle closeFile];//關閉handle

二、內容讀取

讀取文件filehandletest.txt的內容

 

NSString *homePath = NSHomeDirectory();
        NSString *filePath = [homePath stringByAppendingPathComponent:@"filehandletest.txt"];
        NSFileHandle *handle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
        NSData *data = [handle readDataToEndOfFile];
        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",str);
        [handle closeFile];


三、文件的複製

直接代碼註釋

        

NSString *homePath = NSHomeDirectory();
        NSString *filePath = [homePath stringByAppendingPathComponent:@"filehandletest.txt"];//源文件
        NSFileManager *fileManager = [NSFileManager defaultManager];//取得fileManager創建目標文件
        NSString *directionPath = [homePath stringByAppendingPathComponent:@"directionpath.txt"];//取得目標文件目錄
        BOOL createSuccess =  [fileManager createFileAtPath:directionPath contents:nilattributes:nil];
        if (createSuccess) {
            NSLog(@"create success!!!");//判斷是否創建成功
        }
        NSFileHandle *outFileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];//創建讀取文件的handle
        NSFileHandle *inFileHandle = [NSFileHandle fileHandleForWritingAtPath:directionPath];//創建寫入文件的handle
        NSData *data = [outFileHandle readDataToEndOfFile];//讀取數據到data
        [inFileHandle writeData:data];//數據寫入到目標文件
        [outFileHandle closeFile];
        [inFileHandle closeFile];//關閉handle


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章