使用NSFileManager
類可以進行檔處理,這些示例不適用於線上編譯器。
檔處理中使用的方法
下麵列出了用於訪問和操作檔的方法列表。 在這裏,必須將FilePath1
,FilePath2
和FilePath
字串替換為所需的完整檔路徑,以獲得所需的操作。
1. 檢查檔是否存在於路徑中
NSFileManager *fileManager = [NSFileManager defaultManager];
//Get documents directory
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];
if ([fileManager fileExistsAtPath:@""] == YES) {
NSLog(@"File exists");
}
2. 比較兩個檔內容
if ([fileManager contentsEqualAtPath:@"FilePath1" andPath:@" FilePath2"]) {
NSLog(@"Same content");
}
3. 檢查是否可寫,可讀和可執行
if ([fileManager isWritableFileAtPath:@"FilePath"]) {
NSLog(@"isWritable");
}
if ([fileManager isReadableFileAtPath:@"FilePath"]) {
NSLog(@"isReadable");
}
if ( [fileManager isExecutableFileAtPath:@"FilePath"]) {
NSLog(@"is Executable");
}
4. 移動檔
if([fileManager moveItemAtPath:@"FilePath1"
toPath:@"FilePath2" error:NULL]) {
NSLog(@"Moved successfully");
}
5. 複製檔
if ([fileManager copyItemAtPath:@"FilePath1"
toPath:@"FilePath2" error:NULL]) {
NSLog(@"Copied successfully");
}
6. 刪除檔
if ([fileManager removeItemAtPath:@"FilePath" error:NULL]) {
NSLog(@"Removed successfully");
}
7. 讀取檔
NSData *data = [fileManager contentsAtPath:@"Path"];
8. 寫入檔
[fileManager createFileAtPath:@"" contents:data attributes:nil];
前面已成功學習了各種檔訪問和操作技術,現在你應該對檔進行各種操作以及檔的使用所有瞭解。
上一篇:
Objective_C基礎框架
下一篇:
Objective-C快速枚舉