Objective-c-file-handling

提供:Dev Guides
移動先:案内検索

Objective-Cでのファイル処理

ファイル処理は、NSFileManagerクラスの助けを借りて利用可能になります。 これらの例は、オンラインコンパイラでは機能しません。

ファイル処理で使用されるメソッド

ファイルへの*アクセス*および*操作*に使用されるメソッドのリストを以下に示します。 ここでは、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");
}

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];

さまざまなファイルのアクセスおよび操作のテクニックを学習しました。今度は、ファイルに対してさまざまな操作を行い、ファイルの使用法を知るときです。