Detailed iOS file System file directory read and write operations-standby

Source: Internet
Author: User

iphone file reading and writing system operation tutorial is the content of this article, for a run in the iphone app, it can only access some of its own root directory files (so-called sandbox). Once an app is posted on the iphone, it has the following directory structure:
1, which gets the app root can be accessed with nshomedirectory ();
2. Documents directory is the place where we can write and save files, which can be obtained by the following code.

Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory,
Nsuserdomainmask, YES); NSString *documentsdirectory = [Paths objectatindex:0];

3, the TMP directory we can write some programs in the operation of the need to use data, the data written in the program after the exit will not. Can be passed NSString *nstemporarydirectory (void); Method obtained;
4, file Some of the main operations can be operated through the nsfilemanage, can be [Nsfilemanger Defaultmanger] to get its instance. Some operations are related to:
Create a Directory

For example, to create a test directory under Documents,

Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);
NSString *documentsdirectory = [Paths objectatindex:0];
NSLog (@ "%@", documentsdirectory);
Nsfilemanager *filemanage = [Nsfilemanager Defaultmanager];
NSString *mydirectory = [documentsdirectory stringbyappendingpathcomponent:@ "test"];
BOOL OK = [filemanage createdirectoryatpath:mydirectory withintermediatedirectories:yes Attributes:nil Error:nil];
  

Get all filenames under a directory: (as in mydirectory above) available

Nsarray *file = [FileManager subpathsofdirectoryatpath:mydirectory error:nil];
Or
Nsarray *files = [FileManager subpathsatpath:mydirectory];


Read a file: NSData *data = [Filemanger contentsatpath:myfilepath];//myfilepath is a file name that contains the full path or a class method that uses NSData directly:
NSData *data = [NSData Datawithcontentofpath:myfilepath];
  

Save a file:
Can be used Nsfilemanager-(BOOL) Createfileatpath: (NSString *) path contents: (NSData *) Data attributes: (Nsdictionary *) attr;
or NSData.
-(BOOL) WriteToFile: (NSString *) path atomically: (bool) useauxiliaryfile;
-(BOOL) WriteToFile: (NSString *) path options: (Nsuinteger) Writeoptionsmask error: (Nserror *) errorptr;


The Nsfilemanager contains methods for querying the Word library directory, creating, renaming, deleting directories, and getting/setting file properties (readability, authoring, and so on).
Each program will have its own sandbox, through which you can read/write files. Files written to the sandbox will remain stable in the process of the program, even if the actual program is updated.
As shown below, you can locate the file directory in the sandbox:

For error messages
Nserror *error;
Creating a File Manager
Nsfilemanager *filemgr = [Nsfilemanagerdefaultmanager];
Point to file directory
NSString *documentsdirectory= [Nshomedirectory ()
stringbyappendingpathcomponent:@ "Documents"];
Create a Directory
[[Nsfilemanager Defaultmanager]
Createdirectoryatpath: [NSString stringwithformat:@ "%@/myfolder", Nshomedirectory ()]
Attributes:nil];
  

Create a file
Now that we have the file directory, we can use this path to create a new file in the sandbox and write a piece of code:

File we want to creating in the documents directory we want to create will appear in the file directories
Result is:/documents/file1.txt result:/documents/file1.txt
NSString *filepath= [Documentsdirectory
stringbyappendingpathcomponent:@ "File1.txt"];
The string that needs to be written
NSString *str= @ "Iphonedeveloper tips\nhttp://iphonedeveloptips,com";
Write file
[Str Writetofile:filepath Atomically:yes
Encoding:nsutf8stringencoding error:&error];
Displaying the contents of a file directory
NSLog (@ "documentsdirectory:%@",
[Filemgr contentsofdirectoryatpath:documentsdirectoryerror: &error]);
We build a path (file1.txt) for the file we want to create, initialize a string to write to the file, and list the directories. The last line shows a list of directories that appear in the file directory after we create the file:
Renaming a file
To rename a file, we need to move the file to a new path. The following code creates the path to the target file that we expect, and then requests that the file be moved and the file directory displayed after the move.

Rename a file by moving the file
NSString *filepath2= [Documentsdirectory
stringbyappendingpathcomponent:@ "File2.txt"];
Determine whether to move
if ([Filemgr moveitematpath:filepath topath:filepath2 error:&error]! = YES)
NSLog (@ "Unable to move file:%@", [Error localizeddescription]);
Displaying the contents of a file directory
NSLog (@ "documentsdirectory:%@",
[Filemgr contentsofdirectoryatpath:documentsdirectoryerror: &error]);
After the file has been moved, the output should look like the following:
Delete a file
To make this technique complete, let's look at how to delete a file:
Determine whether to delete this file in FilePath2
if ([Filemgr removeitematpath:filepath2 error:&error]! = YES)
NSLog (@ "Unable to delete file:%@", [Error localizeddescription]);
Displaying the contents of a file directory
NSLog (@ "documentsdirectory:%@",
[Filemgr contentsofdirectoryatpath:documentsdirectoryerror: &error]);
Once the file has been deleted, as you might expect, the file directory will be automatically emptied:
These examples can teach you only some of the fur on file processing. To get a more comprehensive and detailed explanation, you need to master the knowledge of Nsfilemanager files.
When developing an iphone program, sometimes you need to do something about it. Getting a list of all the files in a directory is one of the basic operations. With this code, you can get a list of files and folders within a directory.

Nsfilemanager *filemanager = [Nsfilemanager Defaultmanager];
Get the list of files and folders in the Application Documents folder here
Nsarray *documentpaths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentdir = [Documentpaths objectatindex:0];
Nserror *error = nil;
Nsarray *filelist = [[Nsarray alloc] init];
FileList is an array of file names and folder names that contain all the files under that folder
FileList = [FileManager contentsofdirectoryatpath:documentdir error:&error];
The following code can list all the subfolder names in a given folder
Nsmutablearray *dirarray = [[Nsmutablearray alloc] init];
BOOL isdir = NO;
The folder name is listed in the FileList obtained in the above program
For (NSString *file in fileList) {
NSString *path = [Documentdir stringbyappendingpathcomponent:file];
[FileManager fileexistsatpath:path isdirectory: (&isdir)];
if (isdir) {
[Dirarray Addobject:file];
}
Isdir = NO; }
NSLog (@ "Every Thing in the dir:%@", fileList);
NSLog (@ "All folders:%@", Dirarray);

Detailed iOS file System file directory read and write operations-standby

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.