Nsfilemanager&&nsfilehandle

Source: Internet
Author: User

Nsfilemanager:
There are 3 folders in the sandbox root directory:
1.Documents
Recommend that the program create the resulting file and the file data generated by the app Browse is saved in this directory
This directory is included in itunes backup and recovery
2.Library
Default settings or other state information for the stored program
1.Caches
Store cache files, save persisted data
Not synced by itunes
Files that typically contain larger files and do not need to be backed up
2.Preferences
3.tmp
Storage of temporary files, not persisted
To get the sandbox and path:
NSString *homepath=nshomedirectory ();

Get the Documents directory path:
NSString *docpath=[nssearchpathfordirectoriesindomains ((NSDocumentDirectory, Nsuserdomainmask, YES) objectAtIndex : 0];

Get the Cache directory path:
NSString *docpath=[nssearchpathfordirectoriesindomains ((Nscachesdirectory, Nsuserdomainmask, YES) objectAtIndex:0] ;

Get the TMP directory path:
NSString *tmppath=nstemporarydirectory ();

To create a folder:
Nsfilemanager *filemanager=[nsfilemanager Defaultmanager];
NSString *docpath=[nssearchpathfordirectoriesindomains ((NSDocumentDirectory, Nsuserdomainmask, YES) objectAtIndex : 0];
NSString *mydirpath=[docpath stringbyappendingpathcomponent:@ "MyDir"];
BOOL result=[filemanager createdirectoryatpath:mydirpath withintermediatedirectories:yes attributes:nil Error:nil];
if (result) {
NSLog (@ "folder creation succeeded");
}else{
NSLog (@ "folder creation failed");
}

To create a file:
Nsfilemanager *filemanager=[nsfilemanager Defaultmanager];
NSString *docpath=[nssearchpathfordirectoriesindomains ((NSDocumentDirectory, Nsuserdomainmask, YES) objectAtIndex : 0];
NSString *mydirpath=[docpath stringbyappendingpathcomponent:@ "MyDir"];
NSString *myfilepath=[mydirpath stringbyappendingpathcomponent:@ "MyFile.txt"];
BOOL Result=[filemanager Createfileatpath:myfilepath Contents:nil Attributes:nil];
if (result) {
NSLog (@ "file creation succeeded");
}else{
NSLog (@ "File creation failed");
}

Write data to file:
NSString *docpath=[nssearchpathfordirectoriesindomains ((NSDocumentDirectory, Nsuserdomainmask, YES) objectAtIndex : 0];
NSString *mydirpath=[docpath stringbyappendingpathcomponent:@ "MyDir"];
String Write
NSString *myfilepath=[mydirpath stringbyappendingpathcomponent:@ "MyFile.txt"];
NSString *[email protected] "test write content";
BOOL result=[content writetofile:myfilepath atomically:yes encoding:nsutf8stringencoding Error:nil];
/* Array write (requires an archive protocol if the element is a custom type object, otherwise the write fails)
NSString *myfilepath=[mydirpath stringbyappendingpathcomponent:@ "MyFile.txt"];
Nsarray *[email protected][@ "a", @ "B", @ "C"];
BOOL result=[content Writetofile:myfilepath Atomically:yes];
*/
/* Dictionary write (if the element is a custom type Object The archive protocol is required, otherwise the write fails)
NSString *myfilepath=[mydirpath stringbyappendingpathcomponent:@ "Myfile.plist"];
Nsdictionary *[email protected]{@ "Key1": @ "value1", @ "Key2", @ "value2"};
BOOL result=[content Writetofile:myfilepath Atomically:yes];
*/
/* Mixed Data Write
NSString *myfilepath=[mydirpath stringbyappendingpathcomponent:@ "MyFile.txt"];
NSString *temp = @ "Nihao World";
int dataint = 1234;
float datafloat = 3.14f;
Nsmutabledata *writer = [[Nsmutabledata alloc] init];
[writer Appenddata:[temp datausingencoding:nsutf8stringencoding]];
[Writer Appendbytes:&dataint length:sizeof (dataint)];
[Writer Appendbytes:&datafloat length:sizeof (datafloat)];
[Writer Writetofile:myfilepath Atomically:yes];
*/
if (result) {
NSLog (@ "Data write success");
}else{
NSLog (@ "Data write Failed");
}

Read file data:
NSString *docpath=[nssearchpathfordirectoriesindomains ((NSDocumentDirectory, Nsuserdomainmask, YES) objectAtIndex : 0];
NSString *mydirpath=[docpath stringbyappendingpathcomponent:@ "MyDir"];
Read string contents
NSString *myfilepath=[mydirpath stringbyappendingpathcomponent:@ "MyFile.txt"];
NSString *content=[nsstring Stringwithcontentsoffile:myfilepath encoding:nsutf8stringencoding Error:nil];
/* Reading Group contents
NSString *myfilepath=[mydirpath stringbyappendingpathcomponent:@ "MyFile.txt"];
Nsarray *content=[nsarray Arraywithcontentsoffile:myfilepath];
*/
/* Read Dictionary Contents
NSString *myfilepath=[mydirpath stringbyappendingpathcomponent:@ "Myfile.plist"];
Nsdictionary *content=[[nsdictionary Alloc]initwithcontentsoffile:myfilepath];
*/
/* Read mixed data
NSString *myfilepath=[mydirpath stringbyappendingpathcomponent:@ "MyFile.txt"];
int intdata;
float floatdata = 0.0;
NSString *stringdata;
NSData *reader = [NSData Datawithcontentsoffile:myfilepath];
StringData = [[NSString alloc] Initwithdata:[reader subdatawithrange:nsmakerange (0, [temp length])] Encoding: Nsutf8stringencoding];
[Reader Getbytes:&intdata range:nsmakerange ([temp length], sizeof (Intdata))];
[Reader Getbytes:&floatdata range:nsmakerange ([temp length] + sizeof (intdata), sizeof (Floatdata))];
*/

To delete a file:
Nsfilemanager *filemanager=[nsfilemanager Defaultmanager];
NSString *docpath=[nssearchpathfordirectoriesindomains ((NSDocumentDirectory, Nsuserdomainmask, YES) objectAtIndex : 0];
NSString *mydirpath=[docpath stringbyappendingpathcomponent:@ "MyDir"];
NSString *myfilepath=[mydirpath stringbyappendingpathcomponent:@ "MyFile.txt"];
BOOL Result=[filemanager Removeitematpath:myfilepath Error:nil];
if (result) {
NSLog (@ "file deletion succeeded");
}else{
NSLog (@ "File deletion failed");
}

To modify a file:
Writes the new data to the old data corresponding path to overwrite can

Determine if the file exists:
Nsfilemanager *filemanager=[nsfilemanager Defaultmanager];
NSString *docpath=[nssearchpathfordirectoriesindomains ((NSDocumentDirectory, Nsuserdomainmask, YES) objectAtIndex : 0];
NSString *mydirpath=[docpath stringbyappendingpathcomponent:@ "MyDir"];
NSString *myfilepath=[mydirpath stringbyappendingpathcomponent:@ "MyFile.txt"];
BOOL Ishad=[filemanager Isexecutablefileatpath:myfilepath];
if (Ishad) {
NSLog (@ "file exists");
}else{
NSLog (@ "file does not exist");
}


Nsfilemanager Common methods:
-(BOOL) removeItemAtPath: (NSString *) path error: (NSERROR * *) error
Delete the file represented by path

-(BOOL) Moveitematpath: (NSString *) Srcpath Topath: (NSString *) Dstpath Error: (NSERROR *) error
To move or rename a file, the file represented by to cannot be a file that already exists

-(BOOL) contentsequalatpath:path1 andpath:path2
Compare files represented by path1 and path2

-(BOOL) Fileexistsatpath:path
Check if the file represented by path exists

-(BOOL) Isreadablefileatpath:path
Check if the file represented by path exists, is readable

-(BOOL) Iswritablefileatpath:path
Check if the file represented by path exists, is writable

-(Nsdictionary *) Fileattributesatpath:path Traverselink: (BOOL) flag
Gets the file attributes that path represents

-(BOOL) changefileattributes:attr Atpath:path
Change file properties

-(NSString *) Currentdirectorypath
Get current directory

-(BOOL) Changecurrentdirectorypath:path
Change the current directory

-(BOOL) Copyitematpath: (NSString *) Srcpath Topath: (NSString *) Dstpath Error: (NSERROR *) error
Copy directory structure, to cannot already exist

-(BOOL) Createdirectoryatpath:path attributes:attr
Create a Directory

-(BOOL) Fileexistsatpath: (NSString *) path;
Whether the path file exists

-(BOOL) Fileexistsatpath:path isdirectory: (BOOL *) flag
Test whether the file is a directory (flag storage structure yes/no)

-(Nsarray *) Contentsofdirectoryatpath: (NSString *) path error: (NSERROR * *) error
List contents of a directory

-(Nsdirectoryenumerator *) Enumeratoratpath:path
Enumerating the contents of a directory

-(BOOL) Removefileatpath:path Handler:handler
Delete Empty Directory


Common path (NSString object) tool methods
-(NSString *) pathwithcomponents:components
Constructing valid paths based on elements in components

-(Nsarray *) pathcomponents
The destructor path that gets the parts of the path

-(NSString *) lastpathcomponent
Extract the last component of a path

-(NSString *) pathextension
Path name 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 a path

-(NSString *) stringbydeletingpathextension
Remove the extension of the last part of the path

-(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


Nsfilehandle method
+ (Nsfilehandle *) Filehandleforreadingatpath:path
Open a file ready to read

+ (Nsfilehandle *) Filehandleforwritingatpath:path
Open a file ready to write

+ (Nsfilehandle *) Filehandleforupdatingatpath:path
Open a file for update (read and write)

-(NSData *) availabledata
Returning available data from a device or channel

-(NSData *) readdatatoendoffile
Reads the rest of the data until the end of the file (up to Uint_max bytes)

-(NSData *) Readdataoflength: (unsigned int) bytes
Reads the specified number of bytes contents from a file

-(void) Writedata:data
Write data to File

-(unsigned long long) offsetinfile
Gets the offset of the current file

-(void) Seektofileoffset:offset
Sets the offset of the current file

-(unsigned long long) seektoendoffile
Positions the offset of the current file at the end of the file

-(void) Truncatefileatoffset:offset
Set the length of the file to offset bytes

-(void) CloseFile
Close File

Use demonstration:
The 10th byte to navigate to the file (the handle of the file is Databasehandle)
[Databasehandle Seektofileoffset:10];

Get the relative file position by getting the current file offset, and then adding or subtracting this value
[Databasehandle Seektofileoffset:[databasehandle Offsetinfile] + 128];

Moves back 5 integers in a file to the end of the child
[Databasehandle seektofileoffset:[databasehandle Offsetinfile]-5 * sizeof (int)];


Append data to a file
NSString *homepath = Nshomedirectory ();
NSString *sourcepath = [HomePath stringbyappendingpathconmpone:@ "Testfile.text"];
Nsfilehandle *fielhandle = [Nsfilehandle Filehandleforupdatingatpath:sourcepath];
[FileHandle Seektoendoffile]; To jump a node to the end of a file
NSString *str = @ "Append data"
nsdata* stringdata = [str datausingencoding:nsutf8stringencoding];
[FileHandle Writedata:stringdata]; Append Write Data
[FileHandle CloseFile];

//Positioning data
Nsfilemanager *FM = [Nsfilemanager Defaultmanager];
NSString *content = @ "abcdef";
[FM createfileatpath:path contents:[content datausingencoding:nsutf8stringencoding] attributes:nil];
Nsfilehandle *filehandle = [Nsfilehandle Filehandleforreadingatpath:path];
Nsuinteger length = [filehandle availabeldata] length]; Gets the data length
[filehandle SEEKTOFILEOFFSET;LENGTH/2]; offset file half
NSData *data = [FileHandle readdatatoendoffile];
[FileHandle CloseFile];

Copying files
Nsfilehandle *infile, *outfile; Input file, output file
NSData *buffer; Buffered data read
Nsfilemanager *filemanager = [Nsfilemanager Defaultmanager];
NSString *homepath = Nshomedirectory ();
NSString *sourcepath = [HomePath stringbyappendingpathcomponent:@ "testfile.txt"]; Source file path
NSString *outpath = [HomePath stringbyappendingpathcomponent:@ "Outfile.txt"]; Output file path
BOOL sucess = [FileManager createfileatpath:outpath contents:nil Attributes:nil];
if (!success) {
return N0;
}
infile = [Nsfilehandle Filehandleforreadingatpath:sourcepath]; Create read source Path file
if (infile = = nil) {
return NO;
}
outfile = [Nsfilehandle Filehandleforreadingatpath:outpath]; Create a disease open file to output
if (outfile = = nil) {
return NO;
}
[OutFile truncatefileatoffset:0]; Set the length of the output file to 0
Buffer = [infile readdatatoendoffile]; Reading data
[OutFile Writedata:buffer]; Write input
[InFile CloseFile]; Close write, input file
[OutFile CloseFile];


Nsfilemanager&&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.