iOS - 檔案處理



無法透過應用程式直觀地說明檔案處理,因此下面說明了用於處理檔案的關鍵方法。請注意,應用程式包只有讀許可權,我們無法修改這些檔案。不過,你可以修改應用程式的文件目錄。

檔案處理中使用的方法

下面討論了用於訪問處理檔案的方法。此處,我們必須將 FilePath1、FilePath2 和 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 = [fileManager contentsAtPath:@"Path"];

寫入檔案

[fileManager createFileAtPath:@"" contents:data attributes:nil];
廣告
© . All rights reserved.