Two ways to manipulate iOS files: Nsfilemanager Operations and flow operations

Source: Internet
Author: User

1. Common Nsfilemanager File methods

-(NSData *) Contentsatpath:path//Read data from a file

-(BOOL) Createfileatpath:path contents: (NSData *) data attributes:attr//write to a file

-(BOOL) Removeitematpath:path error:err//Delete a file

-(BOOL) Moveitematpath:from topath:to error:err//rename or move a file (to cannot be existing)

-(BOOL) Copyitematpath:from topath:to error:err//Copy file (to cannot be existing)

-(BOOL) Contentsequalatpath:path andpath:path2//Compare the contents of two files

-(BOOL) Fileexistatpath:path//test file exists

-(BOOL) Isreadablefileatpath:path//test file exists and can perform read operations

-(BOOL) Iswriteablefileatpath:path//test file exists, and can perform write operations

-(Nsdictionary *) Attributesofitematpath:path error:err//Get the properties of the file

-(BOOL) setattributesofitematpath:attr error:err//Change the properties of a file

2. Using the Catalog

-(NSString *) Currentdirectorypath//Get current directory

-(BOOL) Changecurrentdirectorypath:path//Change the current directory

-(BOOL) Copyitematpath:from topath:to error:err//Copy directory structure (to cannot be existing)

-(BOOL) Createdirectoryatpath:path withintermediatedirectories: (BOOL) flag ATTRIBUTE:ATTR//Create a new directory

-(BOOL) Fileexistatpath:path isdirectory: (bool*) flag//test file is not a directory (flag stored results yes/no)

-(Nsarray *) Contentsofdirectoryatpath:path error:err//List Contents

-(Nsdirectoryenumerator *) Enumeratoratpath:path//Enumerate the contents of the directory

-(BOOL) Removeitematpath:path error:err//Delete empty directory

-(BOOL) Moveitematpath:from topath:to error:err//rename or move a directory (to cannot be existing)

3. Common Path Tool method

+ (NSString *) pathwithcomponens:components//construct a valid path based on elements in components

-(Nsarray *) pathcomponents//destructor path for each part that makes up this path

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

-(NSString *) pathextension//extract its extension from the last component of the path

-(NSString *) Stringbyappendingpathcomponent:path//Add path to the end of an existing path

-(NSString *) Stringbyappendingpathextension:ext//Add the specified extension to the last component of the path

-(NSString *) stringbydeletinglastpathcomponent//Delete the last component of the path

-(NSString *) stringbydeletingpathextension//Remove the extension from the last part of the file

-(NSString *) Stringbyexpandingtileinpath//Expand the path to the user home directory (~) or the home directory of the specified user (~user)

-(NSString *) Stringbyresolvingsymlinksinpath//try to parse the symbolic link in the path

-(NSString *) Stringbystandardizingpath//by trying to parse ~ 、.. (parent directory symbol),. (current directory symbol), and symbolic link to standardize the path

4. Common Path Tool functions

nsstring* nsusername (void)//Returns the login name of the current user

nsstring* nsfullusername (void)//Returns the full user name of the current user

nsstring* nshomedirectory (void)//Returns the path of the current user home directory

nsstring* nshomedirectoryforuser (nsstring* user)//Return to user's home directory

nsstring* nstemporarydirectory (void)//Returns the path directory that can be used to create temporary files

5. Common iOS Directory

Documents (nsdocumentdirectory)//directory for writing application-related data files, files written here in iOS can be shared with itunes and accessed, files stored here are automatically backed up to the cloud

Library/caches (nscachesdirectory)///directory for writing application support files, save the information that the application needs to start again. itunes does not back up the contents of this directory

TMP (use Nstemporarydirectory ())//This directory is used to store temporary files, only the program terminates the need to remove these files, when the application no longer needs these temporary files, should be removed from this directory

Library/preferences//This directory contains the application's preferences file, using the Nsuserdefault class to create, read and modify the preferences file

 two ways to manipulate iOS files: Nsfilemanager operations and flow operations 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: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];

Get file properties method in iphone

-(NSData *) Applicationdatafromfile: (NSString *) fileName
{
    nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask,yes);
    nsstring *documentsdirectory =[paths objectatindex:0];
    nsstring *appfile =[documentsdirectory stringbyappendingpathcomponent:filename];
    nsdata *data =[[[nsdata alloc]initwithcontentsoffile:appfile]autorelease];
    return data;
}


-(void) getfileattributes
{
Nsfilemanager *filemanager = [Nsfilemanager Defaultmanager];
NSString *path = @ "/1ct.rtf";
Nsdictionary *fileattributes = [FileManager fileattributesatpath:path traverselink:yes];
NSLog (@ "@@");
if (fileattributes! = nil) {
NSNumber *filesize;
NSString *fileowner, *creationdate;
NSDate *filemoddate;
NSString *nsfilecreationdate

File size
if (fileSize = [FileAttributes objectforkey:nsfilesize]) {
NSLog (@ "File size:%qi\n", [FileSize Unsignedlonglongvalue]);
}

File creation Date
if (creationdate = [FileAttributes objectforkey:nsfilecreationdate]) {
NSLog (@ "File creationdate:%@\n", creationdate);
Textfield.text=nsfilecreationdate;
}

File owner
if (Fileowner = [FileAttributes objectforkey:nsfileowneraccountname]) {
NSLog (@ "Owner:%@\n", Fileowner);
}

File modification Date
if (filemoddate = [FileAttributes objectforkey:nsfilemodificationdate]) {
NSLog (@ "Modification Date:%@\n", filemoddate);
}
}
else {
NSLog (@ "path (%@) is invalid.", path);
}
}

///////////////////

File type, file thumbnail???

============================

Get the current application's home directory
NSString DirectoryPath =nshomedirectory ();


Get all the files in the current directory
Nsarray directorycontents = [[Nsfilemanager Defaultmanager] directorycontentsatpath:directorypath];

Get a file or folder
NSString *selectedfile = (nsstring*) [directorycontents ObjectAtIndex:indexPath.row];


To spell a full path
[DirectoryPath Stringbyappendingpathcomponent:selectedfile];


BOOL Isdir;

Determine if it is for the directory


if ([[Nsfilemanager Defaultmanager] Fileexistsatpath:selectedpath Isdirectory:&isdir] && isDir)

{//Directory
}

Else

{//File
}

Date formatting
NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];

[Dateformatter Setdatestyle:nsdateformattermediumstyle];

[Dateformatter Settimestyle:nsdateformatternostyle];


Digital formatting

Nsnumberformatter *numberformatter =[[nsnumberformatter alloc] init];

[Numberformatter Setpositiveformat: @ "#,# #0. # # bytes"];

Get file properties

Nsdictionary *fileattributes =[[nsfilemanager Defaultmanager] Fileattributesatpath:directorypath Traverselink:yes];

Gets the date the file was created

NSDate *modificationdate = (nsdate*) [FileAttributes objectforkey:nsfilemodificationdate];

Gets the byte size of the file

NSNumber *filesize = (nsnumber*) [FileAttributes objectforkey:nsfilesize];
Format File size
NSString A = [Numberformatter stringfromnumber:filesize];

Format File creation Date

NSString B =[dateformatter Stringfromdate:modificationdate];


[Numberformatter release];

[Dateformatter release];

Read file contents operation-(void) loadfilecontentsintotextview{

Open a file through a stream

Nsinputstream *inputstream = [[Nsinputstream alloc] initwithfileatpath:filepath];

[InputStream Open];


Nsinteger maxLength = 128;

uint8_t Readbuffer [maxLength];

Whether it has been identified to the end

BOOL endofstreamreached = NO;

Note:this tight loop would block until stream ends

while (! endofstreamreached)

{

Nsinteger bytesread = [InputStream read:readbuffer maxlength:maxlength];

if (bytesread = = 0)

{//file read to last

endofstreamreached = YES;

}

else if (bytesread = =-1)

{//File read error

endofstreamreached = YES;

}

Else

{

NSString *readbufferstring =[[nsstring alloc] initwithbytesnocopy:readbuffer length:bytesread encoding: Nsutf8stringencoding Freewhendone:no];

Load characters continuously into the view

[Self appendtexttoview:readbufferstring];

[Readbufferstring release];

}

}

[InputStream Close];

[InputStream release];

}

The asynchronous file reads, in the network aspect, because the network's unreliability may cause the Nsfilemanager file operation method the blocking, but the flow operation can realize the asynchronous reading.

Nsstream can work asynchronously. You can register a callback function that has a byte-readable time in the stream, and if it is not readable, do not block the callback.

Two ways to manipulate iOS files: Nsfilemanager Operations and flow operations

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.