Работа с файлами в iOS
Введение
Работу с файлами нельзя объяснить непосредственно через приложения. Понять работу с файлами в iOS можно с помощью следующих примеров.
Файловые операции в iOS. Поскольку приложения находятся в песочнице, их права на чтение и запись файлов ограничены, и они могут читать и записывать файлы только в нескольких каталогах.
Методы, используемые при работе с файлами
Ниже перечислены методы, используемые для доступа к файлам и работы с ними.
В следующих примерах необходимо заменить строки 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 = [fileManager contentsAtPath:@"Path"];
Записать файл
[fileManager createFileAtPath:@"" contents:data attributes:nil];Другие расширения