iOS檔案處理
簡介
檔案處理不能直觀的通過應用程式來解釋,我們可以從以下例項來了解IOS的檔案處理。
IOS中對檔案的操作. 因為應用是在沙箱(sandbox)中的,在檔案讀寫許可權上受到限制,只能在幾個目錄下讀寫檔案。
檔案處理中使用的方法
下面列出了用於訪問和操作檔案的方法的列表。
以下例項你必須替換FilePath1、FilePath和FilePath字串為完整的檔案路徑,以獲得所需的操作。
檢查檔案是否存在
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"); }
比較兩個檔案的內容
if ([fileManager contentsEqualAtPath:@"FilePath1" andPath:@" FilePath2"]) { NSLog(@"Same content"); }
檢查是否可寫、可讀、可執行檔案
if ([fileManager isWritableFileAtPath:@"FilePath"]) { NSLog(@"isWritable"); } if ([fileManager isReadableFileAtPath:@"FilePath"]) { NSLog(@"isReadable"); } if ( [fileManager isExecutableFileAtPath:@"FilePath"]){ NSLog(@"is Executable"); }
移動檔案
if([fileManager moveItemAtPath:@"FilePath1" toPath:@"FilePath2" error:NULL]){ NSLog(@"Moved successfully"); }
複製檔案
if ([fileManager copyItemAtPath:@"FilePath1" toPath:@"FilePath2" error:NULL]) { NSLog(@"Copied successfully"); }
刪除檔案
if ([fileManager removeItemAtPath:@"FilePath" error:NULL]) { NSLog(@"Removed successfully"); }
讀取檔案
NSData *data = https://www.itread01.com/ios/[fileManager contentsAtPath:@"Path"];
寫入檔案
[fileManager createFileAtPath:@"" contents:data attributes:nil];