Check if file name exists in document directory
In my application I am using the following code to save images/files into the application’s document directory:
-(void)saveImageDetailsToAppBundle{
NSData *imageData = UIImagePNGRepresentation(userSavedImage); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",开发者_C百科txtImageName.text]]; //add our image to the path
NSLog(fullPath);
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the image
NSLog(@"image saved");
}
However, there is a problem with the image name. If a file exists in the documents directory, the new file with the same name will overwrite the old file. How can I check if the file name exists in the documents directory?
Use NSFileManager
's fileExistsAtPath:
method to check if it exists or not.
usage
if ( ![fileManager fileExistsAtPath:filePath] ) {
/* File doesn't exist. Save the image at the path */
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil];
} else {
/* File exists at path. Resolve and save */
}
if ([[NSFileManager defaultManager] fileExistsAtPath:myFilePath])
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:@"file name"];
if([fileManager fileExistsAtPath:writablePath]){
// file exist
}
else{
// file doesn't exist
}
As Apple Documentation says it is better to perform some action and then handle no file existance than checking if file is existing.
Note: Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior or race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle those errors gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file system race conditions, see “Race Conditions and Secure File Operations” in Secure Coding Guide.
精彩评论