iOS學習之檔案管理工具(NSFileManager)和檔案對接器(NSFileHandle),

來源:互聯網
上載者:User

iOS學習之檔案管理工具(NSFileManager)和檔案對接器(NSFileHandle),
1、檔案管理工具(NSFileManager) 1> 主要作用及功能方法

  • 主要作用:此類主要是對檔案進行的操作(建立/刪除/改名等)以及檔案資訊的擷取。

  • 功能方法:

 2> 建立檔案夾

  建立所需的方法在標頭檔的聲明:

/* createDirectoryAtPath:withIntermediateDirectories:attributes:error: creates a directory at the specified path. If you pass 'NO' for createIntermediates, the directory must not exist at the time this call is made. Passing 'YES' for 'createIntermediates' will create any necessary intermediate directories. This method returns YES if all directories specified in 'path' were created and attributes were set. Directories are created with attributes specified by the dictionary passed to 'attributes'. If no dictionary is supplied, directories are created according to the umask of the process. This method returns NO if a failure occurs at any stage of the operation. If an error parameter was provided, a presentable NSError will be returned by reference.     This method replaces createDirectoryAtPath:attributes: */ 
// 參數1:建立的檔案夾的路徑
// 參數2:是否建立媒介的布爾值,一般為YES
// 參數3: 屬性,沒有就置為nil
// 參數4: 錯誤資訊- (BOOL)createDirectoryAtPath:(NSString *)path withIntermediateDirectories:(BOOL)createIntermediates attributes:(nullable NSDictionary<NSString *, id> *)attributes error:(NSError **)error NS_AVAILABLE(10_5, 2_0);

  執行個體代碼:

    // 建立對象    NSFileManager *manager = [NSFileManager defaultManager];    // 建立路徑    NSString *path = NSHomeDirectory();        path = [path stringByAppendingPathComponent:@"test/myApp"];        NSLog(@"%@", path);        NSError *error = nil;        // 建立檔案夾    BOOL success = [manager createDirectoryAtPath:path                      withIntermediateDirectories:YES                                       attributes:nil                                            error:&error];    NSLog(@"success = %d,error = %@", success,error);
 2> 向檔案夾中添加檔案

  內容寫入方法在標頭檔的聲明:

// 參數1:要寫入內容的檔案的檔案路徑// 參數2:一個BOOL值,一般為YES// 參數3: 編碼方式,一般為UTF8// 參數4:錯誤資訊- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile encoding:(NSStringEncoding)enc error:(NSError **)error;

  執行個體代碼:

    //向檔案夾中添加字串    path = [path stringByAppendingPathComponent:@"zifucuan.txt"];        //初始化一個字串    NSString *string = @"hello";        BOOL success1 = [string writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];        if (success1) {               NSLog(@"成功:%@",path);    }else{        NSLog(@"失敗");    }
 3> 刪除檔案夾中檔案

  刪除檔案方法在標頭檔的聲明:

// 參數1:路徑// 參數2:錯誤資訊- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error NS_AVAILABLE(10_5, 2_0);

  執行個體代碼:

    // 刪除path目錄下的所有檔案    [manager removeItemAtPath:path error:nil];
 4> 檔案移動

  檔案移動方法在標頭檔的聲明:

// 參數1:要移動的檔案路徑// 參數2:要移動到的檔案路徑(目的地)// 參數3:錯誤資訊- (BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error NS_AVAILABLE(10_5, 2_0);

  執行個體代碼:

    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];        // 建立一個檔案夾    NSString *copyPath = [documentPath stringByAppendingPathComponent:@"備份/test.txt"];        // stringByDeletingLastPathComponent 刪除最後一個路徑    [manager createDirectoryAtPath:[copyPath stringByDeletingLastPathComponent]       withIntermediateDirectories:YES                        attributes:nil                             error:nil];    // 定義一個字串    NSString *testStr = @"Hello World";        NSData *data = [testStr dataUsingEncoding:NSUTF8StringEncoding];        // 將內容寫入檔案    [manager createFileAtPath:copyPath                     contents:data                   attributes:nil];        // 建立一個toPath    NSString *toPath = [documentPath stringByAppendingPathComponent:@"hello/copyTest.txt"];        // 建立一個移動到的檔案夾及檔案    [manager createDirectoryAtPath:[toPath stringByDeletingLastPathComponent]       withIntermediateDirectories:YES                        attributes:nil                             error:nil];        BOOL result = [manager moveItemAtPath:copyPath                                   toPath:toPath                                    error:nil];    NSLog(@"result = %d", result);
 5> 檔案copy(拷貝)

  檔案copy(拷貝)方法在標頭檔的聲明:

// 參數1:要拷貝的檔案路徑 
// 參數2:要拷貝到的檔案路徑(目的地)
// 參數3:錯誤資訊
- (BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error NS_AVAILABLE(10_5, 2_0);

  執行個體代碼:

// 路徑使用上面的路徑[manager copyItemAtPath:copyPath                     toPath:toPath                      error:nil];
2、檔案夾處理器(NSFileHandle) 1> 概述
  • NSFileHandle 是非常基礎的只針對檔案內容的操作(寫入,讀取,更新),是把NSData,通過連接器一個位元組一個位元組的寫入/讀取檔案.(NSData <—> NSFileHandle <—> 檔案).

  • 使用情境: 對檔案內容的進行局部修改、追加內容。

  • 使用步驟

     1).檔案對接並擷取一個NSFileHandle對象.

     2).讀寫操作

     3).關閉對接

  注意:NSFileHandle 類並沒有提供建立檔案的功能。必須使用 NSFileManager 方法來建立檔案。因此,在使用表中的方法時,都是保證檔案已經存在,否則返回nil.

 2> 功能方法

 3> 使用NSFileHandle向檔案夾追加內容

  • 通過fileHandle更新
// 參數為檔案路徑+ (nullable instancetype)fileHandleForUpdatingAtPath:(NSString *)path;
  • 搜尋到常值內容末尾方法
// 搜尋到檔案內容的末尾- (unsigned long long)seekToEndOfFile;
  • 執行個體代碼:(使用上面的路徑)
    // 建立handle對象    NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:path];        // 搜尋到常值內容末尾    [fileHandle seekToEndOfFile];        NSString *appendStr = @"我是後來的";        NSData *appendData = [appendStr dataUsingEncoding:NSUTF8StringEncoding];        // 將資料寫入到對接起    [fileHandle writeData:appendData];        // 關閉對接起    [fileHandle closeFile];

  4> 定位元據

  • 通過fileHandle讀取
// 參數為檔案路徑
+ (nullable instancetype)fileHandleForReadingAtPath:(NSString *)path;
  • 擷取檔案中可獲得的資料(所有資料)
@property (readonly, copy) NSData *availableData;
  • 設定檔案的位移量
// 參數為一個和檔案長度有關的數值- (void)seekToFileOffset:(unsigned long long)offset;
  • 從檔案的位移量位置讀取到最後
- (NSData *)readDataToEndOfFile;

執行個體代碼:

    // 將“123456”寫入file2.txt檔案夾中    NSString * content = @"123456";    NSString * filePath2 = [documentPath stringByAppendingPathComponent:@"file2.txt"];    [fileManager createFileAtPath:filePath2 contents:[content dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];        // 通過fileHandle讀取    fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath2];    // 擷取資料長度    NSUInteger length = [[fileHandle availableData] length];    // 設定檔案的位移量為檔案的一半    [fileHandle seekToFileOffset:length/2.0];    // 從檔案的位移量位置讀取到最後    NSData * data = [fileHandle readDataToEndOfFile];    [fileHandle closeFile];    // 列印讀取的字串    NSString * string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];    NSLog(@"%@",string);

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.