IOS讀取文件類和常用方法

字號:


    第一、NSFileHandle
    NSFileManager類主要對文件的操作(刪除、修改、移動、復制等)
    NSFileHandle類主要對文件的內(nèi)容進行讀取和寫入
    第二、NSFileHandle類處理文件的步驟
    創(chuàng)建一個NSFileHandle對象
    對打開的文件進行I/0操作
    關(guān)閉文件
    可以使用NSFileHandle進行斷點續(xù)傳
    第三、實現(xiàn)查找功能的代碼:
    NSString *homePath=NSHomeDirectory();
    NSString *filePath=[homePath stringByAppendingPathComponent:@"Desktop/hello.rtf"];
    NSFileHandle *fileHandle=[NSFileHandle fileHandleForReadingAtPath:filePath];
    NSUInteger length=[fileHandle availableData].length;
    [fileHandle seekToFileOffset:length/2];
    NSData *data=[fileHandle readDataToEndOfFile];
    NSString *str=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@");
    第四、實現(xiàn)追加文件代碼:
    NSString *homePath=NSHomeDirectory();
    NSString *filePath=[homePath stringByAppendingPathComponent:@"Desktop/hello.rtf"];
    NSFileHandle *fileHandle=[NSFileHandle fileHandleForUpdatingAtPath:filePath];
    //[fileHandle seekToEndOfFile];
    [fileHandle seekToFileOffset:10];
    NSString ";
    NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding];
    [fileHandle writeData:data];
    [fileHandle closeFile];
    // insert code here...
    NSLog(@"Hello, World!");
    第五、實現(xiàn)復制文件的代碼:
    NSString *homePath=NSHomeDirectory();
    NSString *filePath=[homePath stringByAppendingPathComponent:@"Desktop/hello.rtf"];
    NSString *objPath=[homePath stringByAppendingPathComponent:@"Desktop/copy.rtf"];
    NSFileManager *fileManager=[NSFileManager defaultManager];
    BOOL success=[fileManager createFileAtPath:objPath contents:nil attributes:nil];
    NSFileHandle *writeFile=[NSFileHandle fileHandleForReadingAtPath:filePath];
    NSFileHandle *objFile=[NSFileHandle fileHandleForWritingAtPath:objPath];
    [objFile readDataToEndOfFile];
    NSData *data=[writeFile readDataToEndOfFile];
    [objFile writeData:data];
    [writeFile closeFile];
    [objFile closeFile];