Ios-file-handling

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

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

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