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");
    }    

2つのファイルの内容を比較する

   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];
その他の拡張