Detailed description of iPhone file read/write System Operation tutorial

Source: Internet
Author: User

IPhone filesThe read/write System Operation tutorial is described in this article.IPhoneApp, which can only access some of its root directoriesFileThe so-called sandbox). An app is releasedIPhoneThe directory structure is as follows:
 
1. The app root can be accessed using NSHomeDirectory;

2. The Documents directory is used for writing and savingFileGenerally, you can use:

 
 
  1. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
  2. NSUserDomainMask, YES);NSString *documentsDirectory = [paths objectAtIndex:0]; 

.

3. In the tmp directory, we can write data that is needed when the program is running. The data written in the tmp directory will not exist after the program exits. You can use NSString * NSTemporaryDirectory (void;

4. file operations can be performed through NSFileManage, And the instance can be obtained through [NSFileManger defaultManger.

Related Operations:

Create a directory: for example, to create a test directory under Documents,

 
 
  1. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
  2. NSString *documentsDirectory = [paths objectAtIndex:0];  
  3. NSLog(@”%@”,documentsDirectory);  
  4. NSFileManager *fileManage = [NSFileManager defaultManager];  
  5. NSString *myDirectory = [documentsDirectory stringByAppendingPathComponent:@“test”];  
  6. BOOL ok = [fileManage createDirectoryAtPath:myDirectory attributes:nil]; 

Obtain all file names in a directory: The above myDirectory) is available.

 
 
  1. NSArray * file = [fileManager subpathsOfDirectoryAtPath: myDirectory error: nil];
  2. Or
  3. NSArray * files = [fileManager subpathsAtPath: myDirectory];

Read an object:

 
 
  1. NSData * data = [fileManger contentsAtPath: myFilePath]; // myFilePath is the file name that contains the complete path or the class method that uses NSData directly:
  2. NSData * data = [NSData dataWithContentOfPath: myFilePath];

Save an object:

You can use NSFileManager's

 
 
  1. -(BOOL) createFileAtPath :( NSString *) path contents :( NSData *) data attributes :( NSDictionary *) attr;
  2.  
  3. Or NSData
  4.  
  5. -(BOOL) writeToFile :( NSString *) path atomically :( BOOL) useAuxiliaryFile;
  6. -(BOOL) writeToFile :( NSString *) path options :( NSUInteger) writeOptionsMask error :( NSError **) errorPtr;

NSFileManager contains methods for querying single-dictionary directories, creating, renaming, and deleting directories, as well as obtaining/setting file attributes for readability and writability ).

Each program has its own sandbox, through which you can read/write files. The files written into the sandbox will remain stable in the Process of the program, even if the program is updated.

You can locate the file directory in the sandbox as follows:

 
 
  1. // For error messages
  2. NSError * error;
  3. // Create a file manager
  4. NSFileManager * fileMgr = [NSFileManagerdefaultManager];
  5. // Point to the file directory
  6. NSString * documentsDirectory = [NSHomeDirectory ()
  7. StringByAppendingPathComponent: @ "Documents"];
  8. // Create a directory
  9. [[NSFileManager defamanager manager]
  10. CreateDirectoryAtPath: [NSString stringWithFormat: @ "% @/myFolder", NSHomeDirectory ()]
  11. Attributes: nil];

Create a file

Now we haveFileDirectory, we can use this path inSandboxCreate a newFileAnd write a piece of code:

 
 
  1. // File we want to create in the specified ents directory the File we want to create will appear in the File directory
  2. // Result is:/Documents/file1.txt. The Result is/Documents/file1.txt.
  3. NSString * filePath = [documentsDirectory
  4. StringByAppendingPathComponent: @ "file1.txt"];
  5. // String to be written
  6. NSString * str = @ "iPhoneDeveloper Tips \ nhttp: // iPhoneDevelopTips, com ";
  7. // Write a file
  8. [Str writeToFile: filePath atomically: YES
  9. Encoding: NSUTF8StringEncoding error: & error];
  10. // Display the contents of the file directory
  11. NSLog (@ "Documentsdirectory: % @",
  12. [FileMgr contentsOfDirectoryAtPath: documentsDirectoryerror: & error]);

Create a program file1.txt for the desired file), initialize a string to write the file, and list the directories. The last line shows a directory list that appears in the file directory after the file is created:

Rename a file

To rename an object, we need to move the object to a new path. The following code creates the desired path of the target file, and then requests to move the file and display the file directory after moving it.

 
 
  1. // Rename the object by moving the object
  2. NSString * filePath2 = [documentsDirectory
  3. StringByAppendingPathComponent: @ "file2.txt"];
  4. // Determine whether to move
  5. If ([fileMgr moveItemAtPath: filePath toPath: filePath2 error: & error]! = YES)
  6. NSLog (@ "Unable to move file: % @", [error localizedDescription]);
  7. // Display the contents of the file directory
  8. NSLog (@ "Documentsdirectory: % @",
  9. [FileMgr contentsOfDirectoryAtPath: documentsDirectoryerror: & error]);
  10. After the file is moved, the output result is shown in:
  11. Delete an object
  12. To complete this technique, let's take a look at how to delete an object:
  13. // Determine whether to delete the file in filePath2
  14. If ([fileMgr removeItemAtPath: filePath2 error: & error]! = YES)
  15. NSLog (@ "Unable to delete file: % @", [error localizedDescription]);
  16. // Display the contents of the file directory
  17. NSLog (@ "Documentsdirectory: % @",
  18. [FileMgr contentsOfDirectoryAtPath: documentsDirectoryerror: & error]);

OnceFileDeleted, as you expected,FileThe directory will be automatically cleared:

These examples can only show you some details about file processing. To get a more comprehensive and detailed explanation, you need to understand the NSFileManager file.

In developmentIPhoneSometimesFilePerform some operations. Obtain allFileList is one of the basic operations. The following code retrieves a list of files and folders in a directory.

 
 
  1. NSFileManager * fileManager = [NSFileManager defaultManager];
  2. // Obtain the list of files and folders in the application Documents folder.
  3. NSArray * documentPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES );
  4. NSString * documentDir = [documentPaths objectAtIndex: 0];
  5. NSError * error = nil;
  6. NSArray * fileList = [[NSArray alloc] init];
  7. // FileList is an array containing the file names and folder names of all files in the folder.
  8. FileList = [fileManager contentsOfDirectoryAtPath: documentDir error: & error];
  9.  
  10. The following code lists the names of all subfolders in a given folder.
  11.  
  12. NSMutableArray * dirArray = [[NSMutableArray alloc] init];
  13. BOOL isDir = NO;
  14. // List the folder names in the fileList obtained in the above section.
  15. For (NSString * file in fileList ){
  16. NSString * path = [documentDir stringByAppendingPathComponent: file];
  17. [FileManager fileExistsAtPath: path isDirectory :( & isDir)];
  18. If (isDir ){
  19. [DirArray addObject: file];
  20. }
  21. IsDir = NO;
  22. }
  23. NSLog (@ "Every Thing in the dir: % @", fileList );
  24. NSLog (@ "All folders: % @", dirArray );

Summary: DetailsIPhone filesThe system operation content has been introduced. I hope this article will help you!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.