Working with files in iOS

Source: Internet
Author: User

Go to: Action on files in Http://marshal.easymorse.com/archives/3340iOS

Because the application is in the sandbox (sandbox), the file read and write permissions are restricted, only a few directories to read and write files:

    • Documents: User data in the app can be placed here, itunes Backup and restore will include this directory
    • TMP: Store temporary files, itunes does not back up and restore this directory, files in this directory may be deleted after the app exits
    • Library/caches: Store cached files, itunes does not back up this directory, files in this directory will not be deleted in the app exit
Create a file in the documents directory

The code is as follows:

Nsarray *paths=nssearchpathfordirectoriesindomains (nsdocumentdirectory
                                              , nsuserdomainmask 
                                             , YES);  
NSLog (@ " Get document Path:%@ ", [Paths objectatindex:0]);

NSString *filename=[[paths objectatindex:0] stringbyappendingpathcomponent:@ "MyFile"];
NSString *[email protected] "a";
NSData *contentdata=[content datausingencoding:nsasciistringencoding];
if ([Contentdata writetofile:filename Atomically:yes]) {
NSLog (@ ">>write OK.");
}

You can login to the device via SSH to see the file generated in the documents directory.

The above is to create an ASCII encoded text file, if you want to take Chinese characters, such as:

NSString *filename=[[paths objectatindex:0] stringbyappendingpathcomponent:@ "MyFile"];
NSString *[email protected] "Genzhen people have interest";
NSData *contentdata=[content datausingencoding:nsunicodestringencoding];
if ([Contentdata writetofile:filename Atomically:yes]) {
NSLog (@ ">>write OK.");
}

If ASCII encoding is also used, no files will be generated. You can use the nsunicodestringencoding here.

With FileZilla download to the created file open, Chinese no problem:

Create a file in another directory

If you want to specify a different file directory, such as the caches directory, you need to replace the Catalog factory constants, the above code is the same:

Nsarray *paths=nssearchpathfordirectoriesindomains (nscachesdirectory
, Nsuserdomainmask
, YES);

Use Nssearchpathfordirectoriesindomains to locate only the caches directory and the documents directory.

TMP directory, can not follow the above method to obtain the directory, there is a function to obtain the application's root directory:

Nshomedirectory ()

This is the parent directory of documents, and of course the parent directory of the TMP directory. Then the file path can be written like this:

NSString *filename=[nshomedirectory () stringbyappendingpathcomponent:@ "Tmp/myfile.txt"];

Or, more directly, you can use this function:

Nstemporarydirectory ()

However, the resulting path would be:

.../tmp/-tmp-/myfile.txt

Working with resource files

Resource files are often used when writing application projects, such as:

After installing to the device, it is in the app directory:

The following code shows how to get to a file and print the contents of the file:

NSString *myfilepath = [[NSBundle Mainbundle]
pathforresource:@ "F"
oftype:@ "TXT"];
NSString *myfilecontent=[nsstring Stringwithcontentsoffile:myfilepath encoding:nsutf8stringencoding Error:nil];
NSLog (@ "Bundel file path:%@ \nfile content:%@", myfilepath,myfilecontent);

Code Run Effect:

Management of the iOS file system Nsfilemanager determines whether a given road strength is a folder

[Self.fileManagerfileExistsAtPath:isDirectory:];

Used to perform general file system operations (reading and writing are done via NSData, et al.).
Key features include: reading data from a file, writing data to a file, deleting files, copying files, moving files, comparing the contents of two files, testing the existence of files, reading/Changing the properties of a file ...
Just Alloc/init An instance and start performing operations. Thread safe.

    • A common way to process files is as follows: Nsfilemanager
Nsfilemanager *filemanager = [[Nsfilemanager alloc]init]; It is better not to use Defaultmanager.
NSData *mydata = [FileManager Contentsatpath:path]; Reading data from a file
[FileManager Createfileatpath:path Contents:mydata attributes:dict];//writes data to a file, and the property dictionary allows you to create
[FileManager Removeitematpath:path Error:err];
[FileManager Moveitematpath:path topath:path2 Error:err];
[FileManager Copyitematpath:path topath:path2 Error:err];
[FileManager Contentsequalatpath:path andpath:path2];
[FileManager Fileexistsatpath:path]; ... ...
    • A common way to handle catalogs is as follows: Nsfilemanager
[FileManager Currentdirectorypath];
[FileManager Changecurrentdirectorypath:path];
[FileManager Copyitematpath:path topath:path2 Error:err];
[FileManager Createdirectoryatpath:path withintermediatedirectories:yes Attributes:nil Error:err];
[FileManager Fileexistsatpath:path Isdirectory:yes];
[FileManager Enumeratoratpath:path];//Get a list of contents of the directory. You can enumerate each file in the specified directory at a time. ... ...
Have a delegate with lots of "should" methods (to does an operation or proceed after an error).
and plenty more. Check out the documentation.

1, the creation of files

-(Ibaction) CreateFile

{

For error messages

Nserror *error;

Creating a File Manager

Nsfilemanager *filemgr = [Nsfilemanager Defaultmanager];

Point to file directory

NSString *documentsdirectory= [Nshomedirectory () stringbyappendingpathcomponent:@ "Documents"];


Create a Directory

[[Nsfilemanager Defaultmanager] Createdirectoryatpath: [NSString stringwithformat:@ "%@/myfolder", NSHomeDirectory () ] Attributes:nil];

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:@ "File2.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:documentsdirectory error:&error]);
}

2. Renaming 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]);

3. 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.

4. Delete all files in the directory

Get file path
-(NSString *) attchmentfolder{

NSString *document = [Nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES) objectAtIndex : 0];

NSString *path = [Document stringbyappendingpathcomponent:@ "Attchments"];


Nsfilemanager *manager = [Nsfilemanager Defaultmanager];


if (![ Manager Contentsofdirectoryatpath:path Error:nil]) {

[Manager Createdirectoryatpath:path Withintermediatedirectories:no Attributes:nil Error:nil];

}
return path;

}

--Clear Attachments
BOOL result = [[Nsfilemanager Defaultmanager] Removeitematpath:[[mopappdelegate instance] attchmentfolder] error:nil];

5. Determine if the file exists

NSString *filepath = [self datafilepath];

if ([[Nsfilemanager Defaultmanager]fileexistsatpath:filepath])

Do some thing

Report:

-(NSString *) DataFilePath

{

Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);

NSString *documentdirectory = [Paths objectatindex:0];

return [documentdirectory stringbyappendingpathcomponent:@ "Data.plist"];

}


Common Path Tool functionsNSString * Nsusername (); Returns the login name of the current user NSString * Nsfullusername (); Returns the full user name of the current user NSString * Nshomedirectory (); Returns the path to the current user's home directory N Sstring * Nshomedirectoryforuser (); Returns the user's home directory NSString * nstemporarydirectory (); Returns the path directory that can be used to create temporary files Common Path Tool methods-(NSString *) pathwithcomponents:components     constructs a valid path based on the elements (Nsarray object)  -(Nsarray * ) Pathcomponents                                             destructor path, get each part of the path  -(NSString *) lastpathcomponent                                          Extract the last component of the path  -(NSString *) pathextension                                              path Extension  -(NSString * ) StringbyappendingpathcompoNent:path                      add path to the end of an existing path  -(NSString *) Stringbyappendingpathextension:ext             add extension name to the last component of the path  -(NSString *) stringbydeletingpathcomponent                              Delete the last part of the path  -(NSString *) stringbydeletingpathextension                              Delete the last part of the path extension  -(NSString *) Stringbyexpandingtildeinpath            Expand the generation of characters in the path to the user home directory (~) or the specified household directory (~user)  -(NSString * ) Stringbyresolvingsymlinksinpath                           attempt to parse a symbolic link in a path  -(NSString *) Stringbystandardizingpath              standardize paths by trying to parse ~ 、..、.、 and Symbolic Links  -  using path NSPathUtilities.hTempDir = Nstemporarydirectory (); Directory name for temporary files PATH = [FM Currentdirectorypath]; [Path lastpathcomponent]; Extract the last file name from the path fullpath = [path stringbyappendingpathcomponent:fname]; append the file name to the end of the road Extenson = [FullPath pathextension];  pathname filename extension homedir = nshomedirectory (); user's home directory component = [Homedir pathcomponents]; Each part of the path Nsprocessinfo class: Allows you to set or retrieve various types of information for a running application (Nsprocessinfo *) ProcessInfo                                     returns information about the current process-(nsarray*) Arguments                                              Returns the parameters of the current process in the form of a NSString object number-(Nsdictionary *) Environment                                      returns a variable/value pair dictionary. Describes the current environment variable-(int) processidentity                                            return process Identity-(NSString *) processName                                          return process Name-(NSString *) globallyuniquestring    Each call to this method returns a different single-value string that can be used to generate a single-value temporary file name    -(NSString *) hostname                                             returns the name of the host system  -(unsigned int) operatingsystem                                    returns the digital  -that represents the operating system (NSString * ) Operatingsystemname                                       return operating system name  -(NSString *) operatingsystemversionstring                                        returns the current version of the operating system-(void) Setprocessname: (NSString *) name                                   set the current process name to name 

============================================================================
Nsfilehandleclass allows you to use files more efficiently.
Can be implemented as follows function
1. Open a file to perform read, write, or update (read/write) operations;
2, in the file to find the specified location;
3. Read a specific number of bytes from a file, or write a specific number of bytes to the file
In addition, the methods provided by the Nsfilehandle class can also be used with various devices or sockets. As a general rule, we have to go through the following three when working with files Steps
1. Open the file and get a Nsfilehandle object (to reference the file in a later I/O operation).
2. Perform I/O operations on open files.
3, close the file.
Nsfilehandle *filehandle = [[Nsfilehandle alloc]init];
FileHandle = [Nsfilehandle Filehandleforreadingatpath:path]; Open a file ready to read
FileHandle = [Nsfilehandle Filehandleforwritingatpath:path];
FileHandle = [Nsfilehandle Filehandleforupdatingatpath:path];
FileData = [FileHandle availabledata]; Returning available data from a device or channel
FileData = [FileHandle readdatatoendoffile];
[FileHandle Writedata:filedata]; Writing NSData data to a file
[FileHandle CloseFile]; Close file ...
Note:The Nsfilehandle class does not provide the ability to create a file, so you must use Nsfilemanager to create the file

Working with files in iOS

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.