iOS Nsfilemanager and Nsfilehandle

Source: Internet
Author: User

In the current level of mobile app temporary cache files gradually increased, in app development for mobile device files more and more, our iOS in the operation of the file mainly involves two classes Nsfilemanager and Nsfilehandle, below we see how to use these two classes:

1. File creation

//Initializes a Nsfilemanager class Defaultmanager method as a singleton pattern, initialized with a singleton patternNsfilemanager * FileManager =[Nsfilemanager Defaultmanager]; //Stitching PathNSString * path=nshomedirectory (); Path=[path stringbyappendingpathcomponent:@"Desktop/date.txt"]; //Create a fileBOOL flag=[FileManager Createfileatpath:path contents:nil Attributes:nil]; if(flag) {NSLog (@"file creation succeeded"); }Else{NSLog (@"File creation failed"); }

2. Create a Directory

Nsfilemanager * FileManager =[Nsfilemanager Defaultmanager]; NSString* path=nshomedirectory (); Path=[path stringbyappendingpathcomponent:@"Desktop/pro/cpp"]; BOOL Flag=[FileManager createdirectoryatpath:path withintermediatedirectories:yes Attributes:nil Error:nil]; if(flag) {NSLog (@"created successfully"); }Else{NSLog (@"creation failed"); }

3. Delete Files and directories

Nsfilemanager * FileManager =[Nsfilemanager Defaultmanager]; NSString* rootpath=nshomedirectory (); NSString* Dirpath=[rootpath stringbyappendingpathcomponent:@"Desktop/newfolder"]; Nsarray* array=[FileManager Contentsofdirectoryatpath:dirpath Error:nil];  for(NSString * STRinchArray) {NSString* newpath=[Dirpath Stringbyappendingpathcomponent:str]; BOOL Flag=[FileManager Removeitematpath:newpath Error:nil]; if(flag) {NSLog (@"Delete succeeded"); }Else{NSLog (@"Delete Failed"); }                }

There are a number of ways we can take a look at the official API, there are a lot of ways we might use it.

// copy a file to another file [FileManager copyitematpath:path1 topath:path2 Error:nil];           // move a file to another file [FileManager moveitematpath:path1 topath:path2 Error:nil];   // get the contents of the file NSData * Readdata=[filemanager Contentsatpath:path]

Case: We can do an example of how to calculate the number of rows in a file, the idea: we first need to read all the information inside the file content, statistics of the number of rows we only need to count the number of line breaks in the file, the example is as follows:

Nsfilemanager * FileManager =[Nsfilemanager Defaultmanager]; NSString* rootpath=nshomedirectory (); NSString* Dirpath=[rootpath stringbyappendingpathcomponent:@"desktop/newfolder/main.m"]; NSData* Data=[FileManager Contentsatpath:dirpath]; NSString* str=[[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]; intCount= (int) [Str componentsseparatedbystring:@"\ n"].count; NSLog (@"the current total number of rows is%d", count);

4. File Write

In the process of reading and writing the file, we use the most of the Nsfilehandler, we do the file operation through this class

 //  Initializes a file handle for writing  Nsfilehandle * f          Ilehandle=[nsfilehandle Filehandleforwritingatpath:filepath]; NSString  * Str=@ " pppppppppppp  Span style= "color: #800000;"               > " ;  //  Move the file cursor to the last position of the file   [FileHandle Seektoendoffile];                NSData  * Data=[str datausingencoding:nsutf8stringencoding];          //  write data   //  When you're done, you need to turn off  [filehandle CloseFile]; 

5, the file read

Nsfilehandle * filehandle=[Nsfilehandle Filehandleforreadingatpath:filepath]; //read to the end of the fileNSData * Data=[FileHandle Readdatatoendoffile]; //positioning the cursor position[FileHandle Seektofileoffset:2]; //Query the number of available data for this file[FileHandle Availabledata]; //reads a file of a specified lengthNSData * Data=[filehandle readdataoflength:3]; NSString* str=[[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]; NSLog (@"%@", str);//Close Handle[FileHandle CloseFile];

Jerry Education
Source:http://www.cnblogs.com/jerehedu/
Copyright Notice: The copyright of this article is Yantai Jerry Education Technology Co., Ltd. and the blog Park is shared, welcome reprint, but without the consent of the author must retain this paragraph statement, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility.
Technical Consultation:

iOS Nsfilemanager and Nsfilehandle

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.