IOS developer _ iPhone developer _ file system nsfilemanager _ How to create, rename, and delete files

Source: Internet
Author: User

Original article: http://blog.sina.com.cn/s/blog_947c4a9f0100z34f.html


Nsfilemanager contains methods for querying single dictionary directories, creating, renaming, and deleting directories, and obtaining/setting file attributes (readability, writability, and so on ).


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:
// For error messages
Nserror * error;
// Create a file manager
Nsfilemanager * filemgr = [nsfilemanagerdefaultmanaGER];
// Point to the file directory
Nsstring * documentsdirectory = [nshomedirectory ()
StringbyappendingpathcomPonent: @ "documents"];

// Create a directory
[[Nsfilemanager defamanager manager] Createdirectoryatpath: [nsstring stringwithformat: @ "% @/myfolder", nshomedirectory ()] attributes: Nil];


Create a file
Now that we have a 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 create in the specified ents directory the file we want to create will appear in the file directory
// Result is:/Documents documents/file1.txt. The result is/documents/file1.txt.
Nsstring * filepath = [documentsdirectory
StringbyappendingpathcomPonent: @ "file1.txt"];
// String to be written
Nsstring * STR = @ "iphonedeveloper tips \ nhttp: // iphonedeveloptips, com ";
// Write a file
[STR writetofile: filepath atomically: Yes
Encoding: nsutf8stringencoding error: & error];
// Display the contents of the file directory
Nslog (@ "documentsdirectory: % @",
[Filemgr contentsofdirectoryatpatH: documentsdirectoryerror: & error]);
Create a folder (file1.txt) for the file you want to create, 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.
// Rename the object by moving the object
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]);
// Display the contents of the file directory
Nslog (@ "documentsdirectory: % @",
[Filemgr contentsofdirectoryatpatH: documentsdirectoryerror: & error]);
After the file is moved, the output result is shown in:

Delete an object
To complete this technique, let's take a look at how to delete an object:
// Determine whether to delete the file in filepath2
If ([filemgr removeitematpath: filepath2 error: & error]! = Yes)
Nslog (@ "unable to delete file: % @", [error localizeddescription]);
// Display the contents of the file directory
Nslog (@ "documentsdirectory: % @",
[Filemgr contentsofdirectoryatpatH: documentsdirectoryerror: & error]);
Once the file is deleted, as you expected, the file 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.

When developing an iPhone program, you sometimes need to perform operations on files. Obtaining the list of all files in a directory is one of the basic operations. The following code retrieves a list of files and folders in a directory.

  1. Nsfilemanager * filemanager = [nsfilemanager defaultmanager];
    // Obtain the list of files and folders in the application documents folder.
            Nsarray * documentpaths = nssearchpathfordirectoriEsindomains (nsdocumentdirectory, nsuserdomainmask, yes );
            Nsstring * documentdir = [documentpaths objectatindex: 0];
            Nserror * error = nil;
            Nsarray * filelist = [[nsarray alloc] init];
    // Filelist is an array containing the file names and folder names of all files in the folder.
            Filelist = [filemanager contentsofdirectoryatpatH: documentdir error: & error];



The following code lists the names of all subfolders in a given folder.

  1. Nsmutablearray * dirarray = [[nsmutablearray alloc] init];
            Bool isdir = no;
    // List the folder names in the filelist obtained in the above section.
            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 );

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.