File Handling - Objective C
File handling is made available with the help of class NSFIleManager.
Methods used in File Handling
The list of the methods used accessing and manipulating files is listed below. Here, we have to replace the FilePath1, FIlePath2 and FIlePath string to our required full file paths to get the desired action.
Check if file exists at a path
Comparing two file contents
Check if writable, readable and executable
Move File
Copy File
Remove File
Read File
NSData *data = [fileManager contentsAtPath :@"Path"];
Write file
[fileManager createFileAtPath :@"" contents : data attributes :nil];
We have successfully learnt on the various file access and manipulation techniques and it's now your time to do various operations on the files and know the usage of files.
Methods used in File Handling
The list of the methods used accessing and manipulating files is listed below. Here, we have to replace the FilePath1, FIlePath2 and FIlePath string to our required full file paths to get the desired action.
Check if file exists at a path
NSFileManager *fileManager = [NSFIleManger defaultManager];
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES];
NSString *documentDirectoryPath = [directoryPaths objectAtIndex : 0];
if( [ fileManager fileExistsAtPath : @""] ==YES)
{
NSLog(@"File Exists");
}
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES];
NSString *documentDirectoryPath = [directoryPaths objectAtIndex : 0];
if( [ fileManager fileExistsAtPath : @""] ==YES)
{
NSLog(@"File Exists");
}
Comparing two file contents
if ([fileManager contentsEqualAtPath :@"FilePath1" andPath : @" FilePath2" ])
{
NSLog(@"Same content");
}
{
NSLog(@"Same content");
}
Check if writable, readable and executable
if( [fileManger isWritableFileAtPath : @"FilePath"] )
{
NSLog(@"isWritable");
}
{
NSLog(@"isWritable");
}
if( [fileManger isReadableFileAtPath : @"FilePath"] )
{
NSLog(@"isReadable");
}
{
NSLog(@"isReadable");
}
if( [fileManger isExecutableFileAtPath : @"FilePath"] )
{
NSLog(@"isExecutable");
}
{
NSLog(@"isExecutable");
}
Move File
if( [fileManger moveItemAtPath : @"FilePath" toPath : @"FIlePath2" error :NULL] )
{
NSLog(@"Moved Successfully");
}
{
NSLog(@"Moved Successfully");
}
Copy File
if( [fileManger copyItemAtPath : @"FilePath" toPath : @"FIlePath2" error :NULL] )
{
NSLog(@"Copied successfully");
}
{
NSLog(@"Copied successfully");
}
Remove File
if( [fileManger removeItemAtPath : @"FilePath" error :NULL] )
{
NSLog(@"Removed successfully");
}
{
NSLog(@"Removed successfully");
}
Read File
NSData *data = [fileManager contentsAtPath :@"Path"];
Write file
[fileManager createFileAtPath :@"" contents : data attributes :nil];
We have successfully learnt on the various file access and manipulation techniques and it's now your time to do various operations on the files and know the usage of files.
No comments: