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

Source: Internet
Author: User

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);
}
}

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

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.