您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

檔案讀寫實作:NSFileHandle 用法詳解

編輯:iOS 開發綜合

概述

NSFileHandle 是對檔案描述符(file descriptor)的物件導向包裝。你可以用它存取檔案、socket、pipe 與裝置相關的資料:對檔案而言能讀、寫與移動讀寫位置;對 socket、pipe 與裝置而言,則能監看資料並以非同步方式處理。

原文是這樣描述的:The NSFileHandle class is an object-oriented wrapper for a file descriptor. You use file handle objects to access data associated with files, sockets, pipes, and devices. For files, you can read, write, and seek within the file. For sockets, pipes, and devices, you can use a file handle object to monitor the device and process data asynchronously.

常用方法

類別方法:fileHandleForUpdatingAtPath: 以更新模式開啟、fileHandleForReadingAtPath: 以讀取模式開啟、fileHandleForWritingAtPath: 以寫入模式開啟,另有對應 URL 的版本。

實例方法:writeData: 寫入資料、readDataToEndOfFile 讀到結尾、readDataOfLength: 讀取指定長度、seekToEndOfFile 移到結尾、closeFile 關閉檔案、availableData 取得目前可讀的資料。

要特別注意:NSFileHandle 並未提供建立、刪除檔案這類操作,這些必須搭配 NSFileManager 完成。兩者一個負責資料流、一個負責檔案系統,是常見的搭配。

介面設計

@property (weak, nonatomic) IBOutlet UITextField *nameField;
@property (weak, nonatomic) IBOutlet UITextField *ageField;
@property (weak, nonatomic) IBOutlet UITextField *emailField;
@property (weak, nonatomic) IBOutlet UITextView  *informationView;

- (IBAction)saveInformation:(id)sender;
- (IBAction)loadInformation:(id)sender;
- (IBAction)tappedEndEditing:(id)sender;
- (IBAction)tapped:(id)sender;

寫入資料

這個範例把姓名、年齡、信箱以 CSV 形式逐列附加到 Documents 目錄下的檔案中。

- (IBAction)saveInformation:(id)sender
{
    NSString *inputString = [NSString stringWithFormat:@"%@ - %@ - %@\n",
                             self.nameField.text, self.ageField.text, self.emailField.text];

    NSString *docDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *filePath = [docDir stringByAppendingPathComponent:@"myInfoList.csv"];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:filePath]) {
        [fileManager createFileAtPath:filePath contents:nil attributes:nil];
        NSLog(@"文件創建成功");
    }

    NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
    [fileHandle seekToEndOfFile];
    [fileHandle writeData:[inputString dataUsingEncoding:NSUTF8StringEncoding]];
    [fileHandle closeFile];

    self.nameField.text  = @"";
    self.ageField.text   = @"";
    self.emailField.text = @"";
}

流程是:先用 NSFileManager 確認檔案是否存在,不存在就建立;接著以更新模式取得 NSFileHandle,把讀寫位置移到結尾,寫入編碼後的資料,最後關閉檔案。seekToEndOfFile 這一步是「附加而非覆寫」的關鍵。

讀取資料

- (IBAction)loadInformation:(id)sender
{
    NSString *docDir  = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *filePath = [docDir stringByAppendingPathComponent:@"myInfoList.csv"];
    NSFileManager *fileManager = [NSFileManager defaultManager];

    if ([fileManager fileExistsAtPath:filePath]) {
        NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];
        NSString *outputString = [[NSString alloc] initWithData:[fileHandle availableData]
                                                       encoding:NSUTF8StringEncoding];
        [fileHandle closeFile];
        self.informationView.text = outputString;
    }
}

availableData 會一次取回目前可讀的全部內容,適合小檔案;若檔案可能很大,改用 readDataOfLength: 分批讀取會更穩妥。

其他小工具方法

// 點擊背景收起鍵盤
- (IBAction)tappedEndEditing:(id)sender
{
    [self.view endEditing:YES];
}

// 清空預覽區
- (IBAction)tapped:(id)sender
{
    self.informationView.text = @"";
}

整體來說,NSFileHandle 適合「持續附加」或「分段讀取」這類串流式的操作;若只是簡單存檔,用 NSData 的 writeToFile: 會更省事。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved