IOS sandbox mechanism and file operations-NSFileManager (3)

Source: Internet
Author: User

Next, iOS sandbox mechanism and file operations (2 ),

Let's see how NSFileManager is used. Including creating files, directories, deleting, and traversing directories.

 

1. Create a directory in Documents

Create a directory named test, first find the directory of Documents,

 

 

NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); NSString * documentsDirectory = [paths objectAtIndex: 0]; NSLog (@ "documentsDirectory % @", documentsDirectory ); NSFileManager * fileManager = [NSFileManager defaultManager]; NSString * testDirectory = [documentsDirectory stringByAppendingPathComponent: @ "test"]; // create a directory [fileManager createDirectoryAtPath: testDirectory metadata: YES attributes: nil error: nil];

 

Start the program. At this time, the directory is created:

 

2. Create a file under the test directory

What should I do when creating a file? The above code testPath uses stringbyappendingpathcomponentto concatenate the file name you want to generate, such as test00.txt. In this way, you can write files under test.

 

TestDirectory is the path generated by the code above. Don't forget. I wrote three files to the test folder, test00.txt, test22.txt, and text.33.txt. Write String.

The implementation code is as follows:

 

NSString * testPath = [testDirectory stringByAppendingPathComponent: @ "test00.txt"]; NSString * testPath2 = [testDirectory Plugin: @ "test22.txt"]; NSString * testPath3 = [testDirectory stringByAppendingPathComponent: @ "test33.txt"]; NSString * string = @ "write content, write String"; [fileManager createFileAtPath: testPath contents: [string dataUsingEncoding: NSUTF8StringEncoding] attributes: nil]; [fileManager createFileAtPath: testPath2 contents: [string dataUsingEncoding: encoding] attributes: nil]; [fileManager createFileAtPath: testPath3 contents: [string dataUsingEncoding: encoding] attributes: nil];

As shown in the figure below, all three files are available and the content is correct.

 

It is easier to create a file in the Documents directory. You don't need to add test to it.

3. Get all file names in the directory Column

Two methods are available: subpathsOfDirectoryAtPath and subpathsAtPath.

 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);      NSString *documentsDirectory = [paths objectAtIndex:0];      NSLog(@"documentsDirectory%@",documentsDirectory);      NSFileManager *fileManage = [NSFileManager defaultManager];      NSString *myDirectory = [documentsDirectory stringByAppendingPathComponent:@"test"];      NSArray *file = [fileManage subpathsOfDirectoryAtPath: myDirectory error:nil];     NSLog(@"%@",file);      NSArray *files = [fileManage subpathsAtPath: myDirectory ];     NSLog(@"%@",files);

Get the file name in the test folder above

Print results

 

23:23:19. 684 IosSandbox [947: f803] fileList :(

". DS_Store ",

"Test00.txt ",

"Test22.txt ",

"Test33.txt"

)

23:23:19. 686 IosSandbox [947: f803] fileLit (

". DS_Store ",

"Test00.txt ",

"Test22.txt ",

"Test33.txt"

)

Both methods are available, and the hidden files are printed.

4. Use fileManager to operate the current directory

 

 

// Create File Manager NSFileManager * fileManager = [NSFileManager defaultManager]; NSArray * paths = catalog (NSDocumentDirectory, NSUserDomainMask, YES); NSString * documentsDirectory = [paths objectAtIndex: 0]; // change to [fileManager changeCurrentDirectoryPath: [documentsDirectory stringByExpandingTildeInPath] under the directory to be operated; // create the file fileName file name, content of the contents file, if there is no content at the beginning, you can set it to nil, the attribute of the attributes file, initially nil NSString * fileName = @ "testFileNSFileManager.txt"; NSArray * array = [[NSArray alloc] initWithObjects: @ "hello world", @ "hello world1", @ "hello world2", nil]; [fileManager createFileAtPath: fileName contents: array attributes: nil];

In this example, testfilensfilemanager.txt is created and three hello world files are written.

 

 

When the changeCurrentDirectoryPath directory is changed to the current operation directory, it is very convenient to read and write files without adding the full path.

5. delete an object

Then, remove the code and click OK.

 

    [fileManager removeItemAtPath:fileName error:nil];

6. Hybrid data read/write

 

Create hybrid data with NSMutableData and write it to the file. And read the data according to the data type.

6.1 write data:

 

NSString * fileName = @ "testFileNSFileManager.txt"; NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); NSString * documentsDirectory = [paths objectAtIndex: 0]; // obtain the file path NSString * path = [documentsDirectory stringByAppendingPathComponent: fileName]; // NSString * temp = @ "nihao world"; int dataInt = 1234; float dataFloat = 3.14f; // create a data buffer NSMutableData * writer = [[NSMutableData alloc] init]; // Add a string to the buffer [writer appendData: [temp dataUsingEncoding: NSUTF8StringEncoding]; // Add other data to the buffer [writer appendBytes: & dataInt length: sizeof (dataInt)]; [writer appendBytes: & dataFloat length: sizeof (dataFloat)]; // write the buffered data to the file [writer writeToFile: path atomically: YES];

Let's take a look at the data:

 


We can see garbled characters. After the Chinese characters are converted to NSData, there is also the int float binary.

6.2 read the data just written:

 

// Read data: int intData; float floatData = 0.0; NSString * stringData; NSData * reader = [NSData dataWithContentsOfFile: path]; 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)]; NSLog (@ "stringData: % @ intData: % d floatData: % f ", stringData, intData, floatData );

The output is as follows:

 

23:51:14. 723 IosSandbox [1285: f803] stringData: nihao hello! IntData: 1234332 floatData: 3.140000

Here, we changed the Chinese character written to hello. Because [temp length] is used to calculate the length, the Chinese character is regarded as one character, and the result is incorrect.

 

 

Example code: https://github.com/schelling/YcDemo

Copyright Disclaimer: This article will be published at http://blog.csdn.net/totogo2010/, and you will be welcomed to enjoy the transfer and sharing. Please respect the work of the author. Keep this note and the author's blog link when reprinting. Thank you.

 

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.