NSFileManager and NSFileHandle for iOS Learning ),

Source: Internet
Author: User

NSFileManager and NSFileHandle for iOS Learning ),
1. File Manager (NSFileManager) 1> main functions and functions

  • Main role: this class is mainly used to perform operations on files (create, delete, and rename files) and obtain file information.

  • Function Method:

2> Create a folder

Create the required method in the header file declaration:

/* CreateDirectoryAtPath: withIntermediateDirectories: attributes: error: creates a directory at the specified path. if you pass 'no' for createIntermediates, the directory must not exist at the time this call is made. passing 'yes' for 'createintermediate' will create any necessary intermediate directories. this method returns YES if all directories specified in 'path' were created and attributes were set. directories are created with attributes specified by the dictionary passed to 'tes buckets '. if no dictionary is supplied, directories are created according to the umask of the process. this method returns NO if a failure occurs at any stage of the operation. if an error parameter was provided, a presentable NSError will be returned by reference. this method replaces createDirectoryAtPath: attributes :*/
// Parameter 1: Path of the created folder
// Parameter 2: whether to create a Boolean value for the media, usually YES
// Parameter 3: Set the attribute to nil if it is not set.
// 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:

// Create object NSFileManager * manager = [NSFileManager defaultManager]; // create path NSString * path = NSHomeDirectory (); path = [path stringByAppendingPathComponent: @ "test/myApp"]; NSLog (@ "% @", path); NSError * error = nil; // create the folder BOOL success = [manager createDirectoryAtPath: path withIntermediateDirectories: YES attributes: nil error: & error]; NSLog (@ "success = % d, error = % @", success, error );
2> Add a file to the folder

The content writing method is declared in the header file:

// Parameter 1: file path of the file to be written // parameter 2: a bool value, usually YES // parameter 3: encoding method, generally, it is UTF8 // parameter 4: error message-(BOOL) writeToFile :( NSString *) path atomically :( BOOL) useAuxiliaryFile encoding :( NSStringEncoding) enc error :( NSError **) error;

Instance code:

// Add the string path = [path stringByAppendingPathComponent: @ "zifucuan.txt"] To the folder; // initialize a string NSString * string = @ "hello"; BOOL success1 = [string writeToFile: path atomically: YES encoding: NSUTF8StringEncoding error: nil]; if (success1) {NSLog (@ "success: % @", path );} else {NSLog (@ "failed ");}
3> delete files in a folder

The file deletion method is declared in the header file:

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

Instance code:

// Delete all objects in the path directory [manager removeItemAtPath: path error: nil];
4> file Movement

File movement method declaration in the header file:

// Parameter 1: Path of the file to be moved // parameter 2: Path of 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 = [Export (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex: 0]; // create a folder NSString * copyPath = [documentPath stringByAppendingPathComponent: @ "backup/test.txt"]; // stringByDeletingLastPathComponent Delete the last path [manager createDirectoryAtPath: [copyPath stringByDeletingLastPathComponent] withIntermediateDirectories: YES attributes: nil error: nil]; // define a string NSString * testStr = @ "Hello World"; NSData * data = [testStr dataUsingEncoding: NSUTF8StringEncoding]; // write the content to the file [manager createFileAtPath: copyPath contents: data attributes: nil]; // create a toPath NSString * toPath = [documentPath stringByAppendingPathComponent: @ "hello/copyTest.txt"]; // create a folder to be moved to and a file [manager createDirectoryAtPath: [toPath stringByDeletingLastPathComponent] withIntermediateDirectories: YES attributes: nil error: nil]; BOOL result = [manager moveItemAtPath: copyPath toPath: toPath error: nil]; NSLog (@ "result = % d", result );
5> file copy)

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

// Parameter 1: Path of the file to be copied
// Parameter 2: Path of the file to be copied (destination)
// Parameter 3: error message
-(BOOL) copyItemAtPath :( NSString *) srcPath toPath :( NSString *) dstPath error :( NSError **) error NS_AVAILABLE (10_5, 2_0 );

Instance code:

// Use the above path [manager copyItemAtPath: copyPath toPath: toPath error: nil];
2. Folder processor (NSFileHandle) 1> Overview
  • NSFileHandle is a basic file-only operation (write, read, update). It writes/reads files in one byte through the NSData connector. (NSData <-> NSFileHandle <-> file ).

  • Application Scenario: Modify or Append content to a file.

  • Procedure

1) file docking and obtaining an NSFileHandle object.

2). read/write operations

3). Close the connection

Note: The NSFileHandle class does not provide the file creation function. You must use the NSFileManager method to create a file. Therefore, when using the methods in the table, ensure that the file already exists; otherwise, nil is returned.

2> functions and methods

3> Use NSFileHandle to Append content to the folder

  • Update using fileHandle
// The parameter is the file path + (nullable instancetype) fileHandleForUpdatingAtPath :( NSString *) path;
  • Method for searching the end of Text Content
// Search the end Of the file content-(unsigned long) seekToEndOfFile;
  • Instance Code: (use the above path)
// Create the handle object NSFileHandle * fileHandle = [NSFileHandle fileHandleForUpdatingAtPath: path]; // search for [fileHandle seekToEndOfFile] at the end of the text content; NSString * appendStr = @ "I am later "; NSData * appendData = [appendStr dataUsingEncoding: NSUTF8StringEncoding]; // write data to [fileHandle writeData: appendData]; // close the [fileHandle closeFile];

4> locate data

  • Read through fileHandle
// The parameter is the file path.
+ (Nullable instancetype) fileHandleForReadingAtPath :( NSString *) path;
  • Obtain the data available in the file (all data)
@property (readonly, copy) NSData *availableData;
  • Set the file offset
// The parameter is a value related to the file length-(void) seekToFileOffset :( unsigned long) offset;
  • Read from the offset of the file to the end
- (NSData *)readDataToEndOfFile;

Instance code:

// NSString * content = @ "123456"; NSString * filePath2 = [documentPath stringByAppendingPathComponent: @ "file2.txt"]; [fileManager createFileAtPath: filePath2 contents: [content dataUsingEncoding: NSUTF8StringEncoding] attributes: nil]; // read fileHandle = [NSFileHandle fileHandleForReadingAtPath: filePath2] Through fileHandle; // obtain the Data length NSUInteger length = [[fileHandle availableData] length]; // set the file offset to half of the file [fileHandle seekToFileOffset: length/2.0]; // read the last NSData * data = [fileHandle readDataToEndOfFile] From the offset position of the file; [fileHandle closeFile]; // print the read string NSString * string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSLog (@ "% @", string );

 

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.