文件操作是 iOS 開發的基礎功。這篇筆記按「管理文件/目錄 → 拷貝移動刪除 → 讀寫內容 → plist specialized 處理」的順序,把 Foundation 中相關 API 梳理一遍。
NSFileManager 是文件管理器類,用於操作文件與目錄。
NSFileManager *file = [NSFileManager defaultManager]; NSFileManager *file2 = [NSFileManager defaultManager];
打印兩者地址即可驗證它是單例:
NSLog(@"file=%p,file2=%p", file, file2);
遍歷分淺度與深度兩種。
a. 淺度遍歷:只遍歷當前這一層文件夾下的所有文件或目錄。
NSError *error = nil;
NSArray *arr = [file contentsOfDirectoryAtPath:PATH error:&error];
if (error) {
// error 有值說明出錯
NSLog(@"error = %@", error);
} else {
NSLog(@"arr = %@", arr);
}
b. 深度遍歷:連同子層目錄一起遍歷。
arr = [file subpathsOfDirectoryAtPath:PATH error:&error];
if (error) {
NSLog(@"error = %@", error);
} else {
NSLog(@"arr = %@", arr);
}
a. 創建文件:先用 fileExistsAtPath 判斷是否已存在,再調用 createFileAtPath。
BOOL bval = [file fileExistsAtPath:CREATE_FILE];
if (bval) {
// 返回值 YES 表示存在,NO 表示不存在
NSLog(@"文件已存在");
} else {
// 參數1:文件路徑 參數2:內容(nil) 參數3:屬性(nil)
bval = [file createFileAtPath:CREATE_FILE contents:nil attributes:nil];
if (bval) {
NSLog(@"文件創建成功"); // YES 成功,NO 失敗
} else {
NSLog(@"文件創建失敗");
}
}
b. 創建目錄:
bval = [file fileExistsAtPath:CREATE_PATH];
if (bval) {
NSLog(@"目錄已存在");
} else {
// 參數1:路徑 參數2:是否創建中間路徑 參數3:屬性 參數4:錯誤
bval = [file createDirectoryAtPath:CREATE_PATH withIntermediateDirectories:YES attributes:nil error:nil];
if (bval) {
NSLog(@"目錄創建成功");
} else {
NSLog(@"目錄創建失敗");
}
}
NSDictionary *dic = [file attributesOfItemAtPath:CREATE_FILE error:nil]; NSLog(@"dic = %@", dic); // NSNumber 是專門存儲數字的類 NSNumber *numA = dic[@"NSFileSize"]; NSNumber *numB = @5; // 字面量語法 NSLog(@"fileSize = %@, numB = %@", numA, numB); // 對象方法:用整型初始化 NSNumber *numC = [[NSNumber alloc] initWithInt:6]; NSLog(@"numC=%@", numC); // 類方法:用浮點型初始化 NSNumber *numD = [NSNumber numberWithFloat:4.5]; NSLog(@"numD=%@", numD);
NSFileManager *file = [NSFileManager defaultManager]; // 參數1:源路徑 參數2:目標路徑 參數3:錯誤提示
拷貝成功的前提是:源文件存在,且目標路徑不存在。
NSError *error = nil;
if ([file fileExistsAtPath:DST_PATH]) {
NSLog(@"目標文件存在,無須拷貝");
} else {
[file copyItemAtPath:SRC_PATH toPath:DST_PATH error:&error];
if (error) {
NSLog(@"error = %@", error);
} else {
NSLog(@"拷貝成功");
}
}
同樣要求源文件存在、目標路徑不存在。
if ([file fileExistsAtPath:SRC_PATH] && ![file fileExistsAtPath:DST_PATH]) {
[file moveItemAtPath:SRC_PATH toPath:DST_PATH error:&error];
if (error) {
NSLog(@"error = %@", error);
} else {
NSLog(@"文件的移動成功");
}
} else {
NSLog(@"不能確保源文件存在、目標文件不存在");
}
刪除的條件最寬鬆:只要指定路徑存在即可刪除成功。
[file removeItemAtPath:DEL_PATH error:&error];
if (error) {
NSLog(@"error=%@", error);
} else {
NSLog(@"刪除成功");
}
NSFileManager *file = [NSFileManager defaultManager];
NSArray *array = [file contentsOfDirectoryAtPath:PATH error:nil];
NSLog(@"array = %@", array);
for (NSString *obj in array) {
// [obj pathExtension]:求文件擴展名
if ([[obj pathExtension] isEqualToString:@"png"]) {
// stringByAppendingPathComponent:拼接文件路徑
NSString *path = [PATH stringByAppendingPathComponent:obj];
if ([file removeItemAtPath:path error:nil]) {
NSLog(@"%@ 刪除成功", obj);
}
}
}
NSFileHandle 是文件句柄類,用於操作文件內容。三種獲取方式:
fileHandleForReadingAtPath::只讀fileHandleForWritingAtPath::只寫fileHandleForUpdatingAtPath::讀寫(推薦)
NSFileHandle *handle = [NSFileHandle fileHandleForUpdatingAtPath:FILE_P];
if (handle) {
// 拿到句柄即可讀寫文件
}
// 讀取指定長度並存入 NSData // 默認從文件起始位置開始讀 // 設置偏移位置,默認為 0 [handle seekToFileOffset:3]; // 也可以直接偏移到文件末尾 // [handle seekToEndOfFile]; // NSData 是二進制數據流類(非文本文件必須用它,例如視頻流) NSData *data = [handle readDataOfLength:5]; // 從當前位置一直讀到末尾 NSData *data2 = [handle readDataToEndOfFile]; // NSData 轉 NSString NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"str = %@", str); NSString *str2 = [[NSString alloc] initWithData:data2 encoding:NSUTF8StringEncoding]; NSLog(@"str2 = %@", str2);
NSString *str3 = @"hello_1605"; // NSString 轉 NSData NSData *data3 = [str3 dataUsingEncoding:NSUTF8StringEncoding]; // 把游標偏移回起始位置 [handle seekToFileOffset:0]; // 將數據流寫入文件 [handle writeData:data3];
// 參數1:路徑 參數2:編碼 參數3:錯誤
// —— 讀取 ——
NSString *str = [NSString stringWithContentsOfFile:PATH encoding:NSUTF8StringEncoding error:nil];
NSLog(@"str = %@", str);
// —— 寫入 ——
NSString *str2 = @"hello world!";
// 寫入後會替換原文件中的全部內容
if ([str2 writeToFile:PATH atomically:YES]) {
NSLog(@"文件寫入成功");
}
NSFileManager *file = [NSFileManager defaultManager];
// 1. 創建目錄
if ([file fileExistsAtPath:DIR_PATH]) {
NSLog(@"該目錄已存在");
} else {
BOOL bval = [file createDirectoryAtPath:DIR_PATH withIntermediateDirectories:YES attributes:nil error:nil];
if (bval) {
NSLog(@"目錄創建成功");
} else {
NSLog(@"目錄創建失敗");
return 0;
}
}
// 2. 把字符串寫入目錄下的文件
NSString *str = @"I am a handsome man";
if ([str writeToFile:FILE_PATH atomically:YES]) {
NSLog(@"文件寫入成功");
} else {
NSLog(@"文件創建失敗");
}
// 3. 讀取文件內容(跳過前 7 個字符)
NSFileHandle *handle = [NSFileHandle fileHandleForUpdatingAtPath:FILE_PATH];
if (handle) {
[handle seekToFileOffset:7];
NSData *data = [handle readDataToEndOfFile];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"str = %@", str);
}
plist 有三個特點:
1. 以列表方式存儲數據的文件;
2. 只能以數組或字典類型進行存儲;
3. 用字典寫入就用字典讀,用數組寫入就用數組讀。
1. 手動寫入:新建文件 → Resource → Property List,然後在 Xcode 中直接編輯。讀取時按字典接收:
// dictionaryWithContentsOfFile: 以字典方式讀取 plist NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:PATH]; NSLog(@"dic = %@", dic);
2. 代碼寫入:字典與數組都支持 writeToFile:atomically:。
NSNumber *numA = @333;
NSArray *array = @[@"111", @"222", numA];
if ([array writeToFile:PLIST atomically:YES]) {
NSLog(@"寫入成功");
} else {
NSLog(@"寫入失敗");
}
按數組方式讀取:
// arrayWithContentsOfFile: 以數組方式讀取 plist NSArray *array2 = [NSArray arrayWithContentsOfFile:PLIST]; NSLog(@"array = %@", array2);
1. 單例
a. 概念:程序執行過程中只初始化一次;
b. 作用:節約內存,共享數據,方便傳值。
2. NSFileManager —— 文件管理器類,操作文件或目錄
a. 遍歷:深度遍歷 / 淺度遍歷;
b. 創建文件與目錄、判斷是否存在、獲取屬性;
c. 拷貝 / 移動 / 刪除文件或目錄。
3. NSFileHandle —— 文件句柄類,操作文件內容
a. 主要用於文件的讀與寫;
b. 讀寫過程中如何偏移游標;
c. NSData 與 NSString 之間的轉換。
4. 文本文件的讀寫
a. 直接通過字符串讀寫;
b. 讀取時一次讀整體數據,寫入時會覆蓋文件原始內容。
5. plist
a. 以列表方式存儲數據的文件;
b. 只能以數組或字典類型存儲;
c. 字典寫字典讀,數組寫數組讀。