iOS Learning File Manager (Nsfilemanager) and file Locator (Nsfilehandle)

Source: Internet
Author: User
Tags file copy

1. File Manager (Nsfilemanager)1> Creating a folder

Create the declaration of the desired method in the header file:

/* createDirectoryAtPath:withIntermediateDirectories:attributes:error:creates a Directory at the specified path. If you pass the "NO" for Createintermediates, the directory must not exist at the time the "This" is made. Passing ' YES ' for ' createintermediates ' would create any necessary intermediate directories. This method returns YES if any directories specified in ' path ' were created and attributes were set. Directories is created with attributes specified by the dictionary passed to ' attributes '. If No dictionary is supplied, directories was created according to the umask of the process. This method returns NO if a failure occurs on any stage of the operation.     If An error parameter is provided, a presentable nserror would be returned by reference. This method replaces createdirectoryatpath:attributes: */
Parameter 1: path to the created folder
Parameter 2: Whether to create a Boolean value for the media, generally yes
parameter 3: attribute, not set to nil
parameter 4: Error message-(BOOL) Createdirectoryatpath: (NSString *) path withintermediatedirectories: (BOOL) createintermediates attributes: ( Nullable nsdictionary<nsstring *,ID> *) Attributes Error: (NSERROR * *) Error ns_available (10_5, 2_0);

Instance code:

    //Creating ObjectsNsfilemanager *manager =[Nsfilemanager Defaultmanager]; //Create PathNSString *path =nshomedirectory (); Path= [path stringbyappendingpathcomponent:@"Test/myapp"]; NSLog (@"%@", path); Nserror*error =Nil; //Create a folderBOOL success =[Manager Createdirectoryatpath:path Withintermediatedirectories:yes Attributes:nil Error:&ERROR]; NSLog (@"success =%d,error =%@", Success,error);
2> Adding files to a folder

The content -writing method is declared in the header file:

// parameter 1: File path of the file to write to // parameter 2: A bool value, usually yes // Parameter 3: Encoding method, generally UTF8 // Parameter 4: Error message -(BOOL) WriteToFile: (NSString *) path atomically: (BOOL) useauxiliaryfile encoding: (nsstringencoding ) Enc Error: (NSERROR * *) error;

Instance code:

    //to add a string to a folderPath = [path stringbyappendingpathcomponent:@"Zifucuan.txt"]; //Initializes a stringNSString *string=@"Hello"; BOOL Success1= [stringwritetofile:path atomically:yes encoding:nsutf8stringencoding Error:nil]; if(SUCCESS1) {NSLog (@"success:%@", path); }Else{NSLog (@"failed"); }
3> deleting files in a folder

Delete File method in header file declaration:

// parameter 1: path // Parameter 2: Error message -(BOOL) removeItemAtPath: (NSString *) path error: (Nserror *) Error ns_available (10_5, 2_0);

Instance code:

    // Delete all Files    under the path directory [Manager Removeitematpath:path Error:nil];
4> File Movement

  file Move method in header file declaration:

// parameter 1: path of the file to be moved // Parameter 2: path to the file to be moved (destination) // Parameter 3: Error message -(BOOL) Moveitematpath: (NSString *) Srcpath Topath: (NSString *) Dstpath Error: (NSERROR *) Error Ns_ AVAILABLE (10_5, 2_0);

Instance code:

NSString *documentpath = [Nssearchpathfordirectoriesindomains (nsdocumentdirectory, NSUserDomainMask, YES) Objectatindex:0]; //Create a folderNSString *copypath = [Documentpath stringbyappendingpathcomponent:@"Backup/test.txt"]; //stringbydeletinglastpathcomponent Delete the last path[manager Createdirectoryatpath:[copypath Stringbydeletinglastpathcomponent] Withintermediatedirectories:yes    Attributes:nil Error:nil]; //Define a stringNSString *teststr =@"Hello World"; NSData*data =[Teststr datausingencoding:nsutf8stringencoding]; //writing content to a file[manager Createfileatpath:copypath Contents:data Attributes:nil]; //Create a TopathNSString *topath = [Documentpath stringbyappendingpathcomponent:@"Hello/copytest.txt"]; //Create a folder and file to move to[manager Createdirectoryatpath:[topath Stringbydeletinglastpathcomponent] Withintermediatedirectories:yes        Attributes:nil Error:nil]; BOOL result=[Manager Moveitematpath:copypath Topath:topath E    Rror:nil]; NSLog (@"result =%d", result);
5> file copy (copy)

The file copy (copy) method is declared in the header file:

//
parameter 2: to copy
Parameter 3: Error message
-(BOOL) Copyitematpath: (NSString *) Srcpath Topath: (NSString *) Dstpath Error: (NSERROR *) Error ns_available (10_5, 2_0);

Instance code:

// path using the path above [manager Copyitematpath:copypath                     Topath:topath                      Error:nil];
2. Folder Processor (Nsfilehandle)1> using Nsfilehandle to append content to a folder
    • Update via FileHandle
// The parameter is file path + (nullable instancetype) Filehandleforupdatingatpath: (NSString *) path;
    • Search to end of text content method
// Search to end of file content Long long) Seektoendoffile;
    • Instance code: (using the path above)
 //  Create handle object  Nsfilehandle *        FileHandle = [Nsfilehandle Filehandleforupdatingatpath:path];  //  Search to the end of text content   [FileHandle Seektoendoffile]; NSString  *appendstr = @ "  I was later . Span style= "color: #800000;"        > " ;        NSData  *appenddata = [Appendstr datausingencoding:nsutf8stringencoding];  //  writes data to the docking   [FileHandle Writedata:appenddata];  //  close docking  [FileHandle closefile]; 

2> Locating data

    • Read through FileHandle
parameter is file path
+ (Nullable Instancetype) Filehandleforreadingatpath: (NSString *) path;
    • Get data available in a file (all data)
@property (readonly, copy) NSData *availabledata;
    • Set the offset of a file
// parameter is a numeric value associated with the length of the file -(voidlonglong) offset;
    • Read from the offset position of the file to the last
-(NSData *) readdatatoendoffile;

Instance code:

    //write "123456" to the File2.txt folderNSString * content =@"123456"; NSString* FilePath2 = [Documentpath stringbyappendingpathcomponent:@"File2.txt"];        [FileManager createfileatpath:filepath2 contents:[content datausingencoding:nsutf8stringencoding] attributes:nil]; //Read through FileHandleFileHandle =[Nsfilehandle filehandleforreadingatpath:filepath2]; //Get Data lengthNsuinteger length =[[FileHandle availabledata] length]; //set the file offset to half of the file[FileHandle seektofileoffset:length/2.0]; //read from the offset position of the file to the lastNSData * data =[FileHandle Readdatatoendoffile];    [FileHandle CloseFile]; //print a read stringNSString *string=[[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]; NSLog (@"%@",string);

iOS Learning File Manager (Nsfilemanager) and file Locator (Nsfilehandle)

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.