Check whether the file exists in iOS development. If the file does not exist, copy it.

Source: Internet
Author: User

First, we will summarize how to obtain the documents directory. In iOS development, we often need to retrieve the complete path of the documents directory for reading and writing files. I have summarized the following two methods:

1. nsstring * documentsdirectory = [nshomedirectory () stringbyappendingpathcomponent: @ "documents"];

2. nsarray * paths = nssearchpathfordirectoriesindomains (nsdocumentdirectory, nsuserdomainmask, yes );

Nsstring * documentsdirectory = [paths objectatindex: 0];

The documentsdirectory above is the complete path of the obtained documents.

 ProgramAll resource files are stored in the package. The method to obtain the package path is as follows:

Nsstring * appdirectory = [[nsbundle mainbundle] bundlepath];

In actual development, we sometimes need to determine whether a resource file under documents exists. If it does not exist, we will copy it from the package. Now we assume that the file to be determined is "xxx.txt ".CodeAs follows:

Nsfilemanager * filemanager = [nsfilemanager defaultmanager];

Nsstring * filepath = [self [documentsdirectory stringbyappendingpathcomponent: @ "xxx.txt"];

If (! [Filemanager fileexistsatpath: filepath]) // if it does not exist

{

Nslog (@ "xxx.txt is not exist ");

Nsstring * datapath = [[[nsbundle mainbundle] bundlepath] stringbyappendingstring: @ "/xxx.txt"]; // obtain the path of the corresponding file in the package

Nserror * error;

If ([filemanager copyitematpath: datapath topath: filepath error: & error]) // copy

{

Nslog (@ "Copy xxx.txt success ");

}

Else

{

Nslog (@ "% @", error );

}

}

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.