OC Language--nsfilemanager& Nsfilehandle

Source: Internet
Author: User

1. Introduction to Documents

-"What is a file:

File concepts, generalized files, narrow files (disk files),

Common use actions for files (use scenarios where the command line demonstrates file operations).

-"What is a path:

Simply put, in the system, to find a file, the directory ladder to go through.

2. File Management class Nsfilemanager (System Class library )

-"Nsfilemanager" is a singleton class ( for a singleton class, regardless of how many times the object is instantiated, have only one object instance, and this instance is global and can be accessed by the entire system, like a global variable, its data can be shared across the project. )

To manage a file, you must first get the file Manager

Object (Nsfilemanager Class)

nsfilemanager* fm = [Nsfilemanager Defaultmanager];

-"Various actions to manage the file:

A. Traverse directory files (list of file names under directory) (check)

B. Creating a file or directory (Increase)

C. Copying files or directories (Increase)

D. Moving files or directories (change)

E. Deleting a file or directory (delete)

-"Create a File Manager singleton object

NSFILEMANAGER * fm = [Nsfilemanager Defaultmanager];

-"traverse the contents of the directory

Shallow traversal

-(Nsarray *) Contentsofdirectoryatpath: (NSString *) path error: (NSERROR * *) error;

Deep traversal

-(Nsarray *) Subpathsofdirectoryatpath: (NSString *) path error: (NSERROR * *) error;

-"Create a file

Create a normal file

-(BOOL) Createfileatpath: (NSString *) path contents: (NSData *) data attributes: (Nsdictionary *) attr;

Create a Directory

-(BOOL) Createdirectoryatpath: (NSString *) path

Withintermediatedirectories: (BOOL) createintermediates

attributes: (nsdictionary *) attributes

Error: (NSERROR *) error;

-"Copy Files/directories"

-(BOOL) Copyitematpath: (NSString *) Srcpath

Topath: (NSString *) Dstpath

Error: (NSERROR *) error;

-"Move files/directories

-(BOOL) Moveitematpath: (NSString *) Srcpath

Topath: (NSString *) Dstpath

Error: (NSERROR *) error;

-"Delete files/directories

-(BOOL) removeItemAtPath: (NSString *) path

Error: (NSERROR *) error;

-"Get meta information for file attributes//files

-(Nsdictionary *) Attributesofitematpath: (nsstring*) path

Error: (NSERROR *) error;

-"Determine if the file exists

-(BOOL) Fileexistsatpath: (NSString *) path;

Expansion: single-case mode

(1) Single-case mode is a common design pattern.

when applying this pattern, the class of the Singleton object must ensure that only one instance exists, It also instantiates itself and provides this instance to the system as a whole.

That is, for a singleton class, regardless of how many times the object is instantiated, has only one object instance, and this instance is global, can be accessed by the entire system, like a global variable, that can be shared by the entire project with its data.

(2) non-standard single-case design (an optional implementation of the Singleton model)

The singleton creation method usually starts with the default or shared prefix

+ (Myplane *) defaultplane{//or + (Myplane *) sharedplane{     static Myplane * plane = nil;     @synchronized (self) {           if (!plane) {            plane = [[Self alloc] init];           }    }    return plane;}

eg. sample code

#import <foundation/foundation.h>int Main (int argc, const char * argv[]) {@autoreleasepool {nsarray* Mydiraarry          = nil;      Create a File Manager Singleton object nsfilemanager* fm = [Nsfilemanager Defaultmanager];    Shallow traverse mydiraarry = [fm contentsofdirectoryatpath:@ "/users/sub/desktop/" error:nil];      NSLog (@ "%@", Mydiraarry);    Depth traversal mydiraarry=[fm subpathsofdirectoryatpath:@ "/users/sub/desktop" error:nil];        NSLog (@ "%@", Mydiraarry);        [FM createfileatpath:@ "/users/sub/desktop/haha.txt" Contents:nil Attributes:nil];      [FM createdirectoryatpath:@ "/users/sub/desktop/testdir" Withintermediatedirectories:no Attributes:nil Error:nil];    Once again the light traversal mydiraarry = [FM contentsofdirectoryatpath:@ "/users/sub/desktop/" error:nil];      NSLog (@ "%@", Mydiraarry);      Copy file [FM copyitematpath:@ "/users/sub/desktop/test.txt" topath:@ "/users/sub/desktop/test.rtf" error:nil];    Once again the light traversal mydiraarry = [FM contentsofdirectoryatpath:@ "/users/sub/desktop/" error:nil];NSLog (@ "%@", Mydiraarry);      moving files [FM moveitematpath:@ "/users/sub/desktop/test.txt" topath:@ "/users/sub/desktop/testdir/test.txt" error:nil];    Deep traversal mydiraarry = [FM subpathsofdirectoryatpath:@ "/users/sub/desktop/" error:nil];      NSLog (@ "%@", Mydiraarry); Gets the property information for the specified file nsdictionary* fileattributesinfo = [fm attributesofitematpath:@ "/USERS/SUB/DESKTOP/TEST.RTF" Error:nil    ];    NSLog (@ "%@", fileattributesinfo); if ([FM fileexistsatpath:@ "/USERS/SUB/DESKTOP/TESTDIR/TEST.RTF"]) {[FM removeitematpath:@ "/users/sub/desktop/    Testdir/test.rtf "Error:nil";    }else{NSLog (@ "No such file");    }//Deep traversal mydiraarry = [FM subpathsofdirectoryatpath:@ "/users/sub/desktop/" error:nil];    NSLog (@ "%@", Mydiraarry);        nsdictionary* DIC = [fm attributesofitematpath:@ "/USERS/SUB/DESKTOP/TEST.RTF" error:nil];          NSLog (@ "%@", [dic objectforkey:@ "Nsfiletype"]); } return 0;}

3. File handle class Nsfilehandle (System class Library)

The file pointer (file handle) returned to our program by the operating system

    • Read and write files first need Nsfilehandle open file
    • Nsfilehandle are used to read and write files using the NSData type of binary data.
    • The mutual conversion between NSData and NSString

Operation Method:

-"Open File Method"

Open as read-only

+ (ID) Filehandleforreadingatpath: (NSString *) path;

Open in write-only mode

+ (ID) Filehandleforwritingatpath: (NSString *) path;

Open in read and write mode

+ (ID) Filehandleforupdatingatpath: (NSString *) path;

-"read the specified length of data

-(NSData *) Readdataoflength: (nsuinteger) length;

offset of file : also known as a read-write pointer to a file, or a positional pointer, in fact, the position of the offset file at the beginning of the number of characters, is an unsigned long integer data

-Read from current offset to end of file

-(NSData *) readdatatoendoffile;

-"Set file offset

-(void) Seektofileoffset: (unsigned long long) offset;

-"Position the file offset to the end of the file

-(unsigned long long) seektoendoffile;

-"Set the length of the file to offset size (in bytes)

-(void) Truncatefileatoffset:

(unsigned long long) offset;

-"Write File

-(void) WriteData: (NSData *) data;

-"writes buffer contents to disk immediately

-(void) synchronizefile;

eg. sample code

#import <foundation/foundation.h>int Main (int argc, const char * argv[]) {@autoreleasepool {nsstring* myString      = @ "Happy Today";      Encode the information data in the specified format for writing to the file nsdata* aData = [myString datausingencoding:nsutf8stringencoding];        nsmutablestring* bstring = [[Nsmutablestring alloc] Initwithdata:adata encoding:nsutf8stringencoding];    [Bstring appendstring:@ ", HELLO World"];    NSLog (@ "%@", bstring);        AData = [bstring datausingencoding:nsutf8stringencoding];        nsfilemanager* fm = [Nsfilemanager Defaultmanager];      [FM createfileatpath:@ "/users/sub/desktop/new.txt" Contents:adata Attributes:nil];      Open the file in read-write mode (open in updatable mode) nsfilehandle* fh = [Nsfilehandle filehandleforupdatingatpath:@ "/users/sub/desktop/new.txt"];    Read operation of the file AData = [fh Readdataoflength:3];        nsstring* cString = [[NSString alloc] Initwithdata:adata encoding:nsutf8stringencoding];    NSLog (@ "%@", cString);    [FH Seektofileoffset:10];    AData = [FH readdatatoendoffile]; Nsstring* dstring = [[NSString alloc] Initwithdata:adata encoding:nsutf8stringencoding];          NSLog (@ "%@", dstring);      emptying the file [FH truncatefileatoffset:0];    Writes encoded data to a file [FH Writedata:adata];  [FH Synchronizefile]; } return 0;}

Expansion: NSData (Data Class)

-"Convert the string to NSData

NSString *str = @ "Welcome to MyHome";

NSData *data = [str datausingencoding:nsutf8stringencoding];

-"Convert NSData to String

NSString *newstr = [[NSString alloc] initwithdata:data encoding:nsutf8stringencoding];

OC Language--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.