IOS-sandbox mechanism (2 file read/write)

Source: Internet
Author: User

I. Directory description
As shown in, a sandbox typically contains the following directories and files.

Description of directories and files:1. DocumentsYou should write all application data files to this directory to store user data or other information that should be regularly backed up.2. AppName. appThis is the application package directory, including the application itself. Because the application must be signed, you cannot modify the content in this directory during runtime. Otherwise, the application may fail to start.3. Library <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Release/CvM/release + xL/release + 5/bPM1tDQ6NKqtcTQxc + ioaMKCjxzdHJvbmc + release/release + G2qsb6y/ nT0LXEdG1wzsS8/qGjCgo8YnI + CgoKPHN0cm9uZz62/iDJs7rQ1tDOxLz + signature + Cgo8YnI + signature/Signature = "path: % @ ", homeDirectory );

// Application Path
NSString * appPath = [[NSBundle mainBundle] resourcePath];
NSLog (@ "path: % @", appPath );
// Document directory
NSArray * docPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES );
NSString * documentPaths = [docPaths objectAtIndex: 0];
NSLog (@ "path: % @", documentPaths );

// Cache directory
NSArray * cacPaths = NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES );
NSString * cachePath = [cacPaths objectAtIndex: 0];
NSLog (@ "% @", cachePath );

// Obtain the Library directory
NSArray * libPaths = NSSearchPathForDirectoriesInDomains (NSLibraryDirectory, NSUserDomainMask, YES );
NSString * libraryPath = [libPaths objectAtIndex: 0];
NSLog (@ "% @", libraryPath );

// Obtain the Tmp directory
NSString * tmpDir = NSTemporaryDirectory ();
NSLog (@ "% @", tmpDir );


}
Output result:14:55:35. 621 ZZFile [12523: 70b] path:/Users/XXXXXX/Library/Application Support/iPhone Simulator/7.0.3/Applications/9170019f-440c-42c3-96e2-848ce9268fef
14:55:35. 623 ZZFile [12523: 70b] path:/Users/XXXXXX/Library/Application Support/iPhone Simulator/7.0.3/Applications/9170019F-379C-42C3-96E2-848CE9268FEF/ZZFile. app2014-04-23 14:55:35. 624 ZZFile [12523: 70b] path:/Users/XXXXXX/Library/Application Support/iPhone Simulator/7.0.3/Applications/9170019f-rjc-42c3-96e2-848ce9268fef/Documents2014-04-23 14:55:35. 626 ZZFile [12523: 70b]/Users/XXXXXX/Library/Application Support/iPhone Simulator/7.0.3/Applications/9170019f-417c-42c3-96e2-848ce9268fef/Library/Caches2014-04-23 14:55:35. 631 ZZFile [12523: 70b]/Users/XXXXXX/Library/Application Support/iPhone Simulator/7.0.3/Applications/9170019f-417c-42c3-96e2-848ce9268fef/Library2014-04-23 14:55:35. 632 ZZFile [12523: 70b]/Users/XXXXXX/Library/Application Support/iPhone Simulator/7.0.3/Applications/9170019f-417c-42c3-96e2-848ce9268fef/tmp/
Example code 2: file read/write-(Void) WRFile
{
// Write data
NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES );
NSString * docDir = [paths objectAtIndex: 0];
If (! DocDir)
{
NSLog (@ "the Documents directory is not found ");
}
NSArray * array = [[NSArray alloc] initWithObjects: @ "Hebie", @ "BJUT", nil];
NSString * filePath = [docDir stringByAppendingPathComponent: @ "zz. text"];
[Array writeToFile: filePath atomically: YES];


// Read data
// NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES );
// NSString * docDir = [paths objectAtIndex: 0];
// NSString * filePath = [docDir stringByAppendingPathComponent: @ "testFile.txt"];
NSArray * result = [[NSArray alloc] initWithContentsOfFile: filePath];
NSLog (@ "% @", result );
}
-(Void) userDefalut
{
NSUserDefaults * defalut = [NSUserDefaults standardUserDefaults];
[Defalut setObject: @ "ZZBJUT" forKey: @ "name"];
[Defalut setObject: [NSNumber numberWithInteger: 25] forKey: @ "age"];
[Defalut synchronize];

Defalut = nil;

Defalut = [NSUserDefaults standardUserDefaults];
NSString * name = [defalut objectForKey: @ "name"];
NSInteger age = [[defalut objectForKey: @ "age"] integerValue];
NSLog (@ "name: % @ age: % d", name, age );

} Output result:14:01:11. 559 ZZFile [12104: 70b] (
Hebie,
BJUT
)
14:01:11. 855 ZZFile [12104: 70b] name: ZZBJUT age: 25

The Documents directory in the sandbox contains one zz. text, and the Preferences directory of the Library contains one com. qiniudn. zhangzhe. ZZFile. plist file, as shown in:

Open the com. qiniudn. zhangzhe. ZZFile. plist file, which contains the data we saved with NSUserDefault.
Open the zz.txt File Hebie BJUT
You can see that the data in the file is stored in the attribute list format.
Run the following code to delete an object: // delete an object
If ([[NSFileManager defaultManager] fileExistsAtPath: finalLocation])
{
RetVal = [[NSFileManager defaultManager] removeItemAtPath: finalLocation error: NULL]; NSLog (@ "delete file: % @", finalLocation );
}

Example code 3: folder operations-(Void) createFolder :( NSString *) createDir
{
BOOL isDir = NO;
NSFileManager * fileManager = [NSFileManager defaultManager];
BOOL existed = [fileManager fileExistsAtPath: createDir isDirectory: & isDir];
If (! (IsDir = YES & existed = YES ))
{
[FileManager createDirectoryAtPath: createDir withIntermediateDirectories: YES attributes: nil error: nil];
}
}
-(Void) folderOperation
{
NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES );
NSString * documentsDirectory = [paths objectAtIndex: 0]; // Get documents folder
NSString * dataPath = [documentsDirectory stringByAppendingPathComponent: @ "first"];
[Self createFolder: dataPath];

DataPath = [dataPath stringByAppendingPathComponent: @ "secode"];
[Self createFolder: dataPath];
// Create a file
NSString * testPath = [dataPath stringByAppendingPathComponent: @ "zz.txt"];
NSString * string = @ "ZZBJUT writing Files ";
NSFileManager * fileManager = [NSFileManager defaultManager];
[FileManager createFileAtPath: testPath
Contents: [string dataUsingEncoding: NSUTF8StringEncoding]
Attributes: nil];
DataPath = [dataPath stringByAppendingPathComponent: @ "third"];
[Self createFolder: dataPath];
}

The content in the sandbox is as follows. You can see that the/first/second/third directory is created in the document directory, and a zz. text file is created in seconde.


Example code 4: copy the files in the app directory to the Document-(Void) copyBundleFileToDocument
{
NSString * flieName = @ "apple.jpg ";
NSString * fileToCopy = [[NSBundle mainBundle] pathForResource: @ "apple.jpg" ofType: nil];

NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES );
NSString * documentsDirectory = [paths objectAtIndex: 0]; // Get documents folder
NSString * dataPath = [documentsDirectory stringByAppendingString: @ "/first/second/third"];
NSString * finalLocation = [dataPath stringByAppendingPathComponent: flieName];

BOOL retVal = YES; // If the file already exists, we'll return success...

If (! [[NSFileManager defaultManager] fileExistsAtPath: finalLocation])
{
RetVal = [[NSFileManager defaultManager] copyItemAtPath: fileToCopy
ToPath: finalLocation
Error: NULL];
NSLog (@ "copy done! ");
NSLog (@ "souce: % @", fileToCopy );
NSLog (@ "destination: % @", finalLocation );
}}
Output result:14:15:35. 262 ZZFile [12218: 70b] copy done!
14:15:35. 265 ZZFile [12218: 70b] souce:/Users/XXXXXX/Library/Application Support/iPhone Simulator/7.0.3/Applications/9170019f-rjc-42c3-96e2-848ce9268fef/ZZFile. app/apple.jpg 14:15:35. 266 ZZFile [12218: 70b] destination:/Users/XXXXXX/Library/Application Support/iPhone Simulator/7.0.3/Applications/9170019f-rjc-42c3-96e2-848ce9268fef/Documents/first/secone2-848ce9268fef
As shown in, copy the apple. jgp file in the app directory to the third folder of Documents.




Note: NSBundle is a directory that contains the resources used by the program, including the image, sound, compiled code, and nib files (bundle is also called plug-in). Corresponding to bundle, cocoa provides the NSBundle class. Bundle is actually a packaging method for applications, just like jar files in java. NSBundle is an abstract representation of bundle. It can be used to conveniently access resources in applications.
In the authorization code, use nsbundleto obtain an image apple.jpg in the program. The path of the output image is as follows:
/Users/XXXXXX/Library/Application Support/iPhone Simulator/7.0.3/Applications/9170019f-440c-42c3-96e2-848ce9268fef/ZZFile. app/apple.jpg

Instance Code 5: List Directory content-(Void) listFile
{
NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES );
NSString * documentsDirectory = [paths objectAtIndex: 0];
NSFileManager * fileManage = [NSFileManager defaultManager];
NSArray * file = [fileManage subpathsOfDirectoryAtPath: documentsDirectory error: nil];
NSLog (@ "% @", file );
}

Output content: 14:31:24. 881 ZZFile [12334: 70b] (
". DS_Store ",
First,
"First/. DS_Store ",
"First/second ",
"First/second/. DS_Store ",
"First/second/third ",
"First/second/third/apple.jpg ",
"First/second/zz.txt ",
"Zz. text"
) Example code 6: hybrid data read/write-(Void) writeMixData
{
NSString * fileName = @ "mixtypedata.txt ";
NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES );
NSString * documentsDirectory = [paths objectAtIndex: 0];
// Obtain the file path
NSString * path = [documentsDirectory stringByAppendingPathComponent: fileName];

// Data to be written
NSString * temp = @ "Hello world! ";
Int dataInt = 1234;
Float dataFloat = 3.14f;

// Create a data buffer
NSMutableData * writer = [NSMutableData alloc] init];
// Add the string to the buffer
[Writer appendData: [temp dataUsingEncoding: NSUTF8StringEncoding];
// Add other data to the buffer
[Writer appendBytes: & dataInt length: sizeof (int)];
[Writer appendBytes: & dataFloat length: sizeof (float)];
// Write the buffered data to the file
[Writer writeToFile: path atomically: YES];

// [Self readMixData];
}
-(Void) readMixData
{
NSString * fileName = @ "mixtypedata.txt ";
NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES );
NSString * documentsDirectory = [paths objectAtIndex: 0];
// Obtain the file path
NSString * path = [documentsDirectory stringByAppendingPathComponent: fileName];


// Read data:
Int intData;
Float floatData = 0.0;
NSString * stringData;

NSData * reader = [NSData dataWithContentsOfFile: path];
StringData = [[NSString alloc] initWithData:
[Reader subdataWithRange: NSMakeRange (0, [@ "Hello world! "Length])]
Encoding: NSUTF8StringEncoding];

[Reader getBytes: & intData range: NSMakeRange ([@ "Hello world! "Length], sizeof (int)];
[Reader getBytes: & floatData range: NSMakeRange ([@ "Hello world! "Length] + sizeof (int), sizeof (float)];
NSLog (@ "stringData: % @ intData: % d floatData: % f", stringData, intData, floatData );
}

Output result:14:44:53. 820 ZZFile [12452: 70b] stringData: Hello world! IntData: 1234 floatData: 3.140000 Note: Garbled characters may occur when the string contains Chinese characters, because [temp length] is used to calculate the length, and the Chinese character is regarded as one character. The result is incorrect.

3. File Operation EncapsulationThe header file ZZFile. h of the encapsulation class ZZFile is as follows: @ interface ZZFile: NSObject/Get Home/Bundle/Document/Library/Cache/Temp Directory
+ (NSString *) HomeDirectory;
+ (NSString *) BundleDirectory;
+ (NSString *) DocumentDirectory;
+ (NSString *) LibraryDirectory;
+ (NSString *) LibraryCacheDirectory;
+ (NSString *) TempDirectory;

// File Path.
+ (NSString *) DocumentFilePath :( NSString *) fileName;
+ (BOOL) FileIsExist :( NSString *) fileName;
+ (BOOL) DocumentFileIsExist :( NSString *) fileName;

// File Operation.
+ (BOOL) WriteObject :( id) object filePath :( NSString *) fileName;
+ (BOOL) WriteObject :( id) object DocumentFilePath :( NSString *) fileName;
+ (BOOL) removeFileAtPath :( NSString *) fileName;
+ (BOOL) removeDocumentFileAtPath :( NSString *) fileName;
+ (BOOL) RenameDocumentFile :( NSString *) oldName forName :( NSString *) newName;
+ (BOOL) CopyDocumentFileFrom :( NSString *) source To :( NSString *) destination;

// Folder Operation.
+ (BOOL) CreateDocumentFolder :( NSString *) folderName;
+ (BOOL) RemoveDocumentFolder :( NSString *) folderName;
+ (BOOL) RenameDocumentFolder :( NSString *) oldName forName :( NSString *) newName;
+ (BOOL) CopyDocumentFolderFrom :( NSString *) source To :( NSString *) destination;
+ (NSArray *) TraverseDocumentFolder :( NSString *) folderName;

// Copy Bundle file To Document
+ (BOOL) CopyBundleFile :( NSString *) fileName ToDocument :( NSString *) documentFileName;

// NSUserDefalut
+ (Void) UserDefalutObject :( id) object forKey :( NSString *) key;
+ (Id) UserDefalutObjectForKye :( NSString *) key;
+ (Void) Synchronize; // Hash File

 
+ (NSString *) md5HashOfFileAtPath :( NSString *) filePath; + (NSString *) sha1HashOfFileAtPath :( NSString *) filePath; + (NSString *) sha512HashOfFileAtPath :( NSString *) filePath; @ end
For details, see github: Https://github.com/ZhangzheBJUT/IOSProject/tree/master/FiltToolZZFile. h and ZZFile. m are simple encapsulation of file operations to facilitate file access and modification.

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.