iOS - file operations (File Operating)

Original link: http://www.cnblogs.com/share-iOS/p/5816419.html

1. Sandbox & NSData

/ * _______________________________ get sandbox path _________________________________________ * /

// The first way to get

        // NSHomeDirectory (); Gets the directory path to the sandbox

        NSString *homePath = NSHomeDirectory();

        NSLog (@ "sandbox directory:% @", homePath);

        

        NSString *docPath1 = [NSString stringWithFormat:@"%@/Documents",homePath];

        NSString *docPath2 = [homePath stringByAppendingString:@"/Documents"];

        

        NSLog(@"\ndocPath1:%@,\ndocPath2:%@",docPath1,docPath2);

        

        // The second acquisition mode.

        /*

         NSDocumentDicrectory: Documents folder

         NSLibraryDirectory: Library folder

         */

        /*

        NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

        NSLog(@"array:%@",array);

 

 

2. 沙盒 & NSData & NSFileManager

(NSFileManager: create files, copy, delete, cut before the file (Note: The operating target for the file, not the file contents))

 

        // demonstration path

        NSString *path = @"/Users/apple/file.text";

        

        // 1. Part of the return path

        NSArray *array = [path pathComponents];

        NSLog(@"pathComponents:%@",array);

        

        The last part // 2. Paths

        NSString *lastPathComponent = [path lastPathComponent];

        NSLog(@"lastComponent:%@",lastPathComponent);

        

        // 3 additional sub-path

        NSString *newPath1 = [path lastPathComponent];

        NSLog(@"newPath1=%@",newPath1);

        

        NSString *newPath2 = [path stringByAppendingPathComponent:@"/appFile.text"];

        NSLog(@"newPath2:%@",newPath2);

        

        // 4. Delete the last part

        NSString *deleteLast = [path stringByDeletingLastPathComponent];

        NSLog(@"deleteLast:%@",deleteLast);

        

        // 5. Delete extension

        NSString *deleteExtension = [path stringByDeletingPathExtension];

        NSLog(@"deleteExtension:%@",deleteExtension);

        

        6 // Get path extension part of the final composition

        NSString *extension =[path pathExtension];

        NSLog(@"extension:%@",extension);

        

        // 7. additional extensions

        NSString *appendExt = [path stringByAppendingPathExtension:@"jpg"];

        NSLog(@"appendExt:%@",appendExt);

        

        

        //NSString->NSData

        NSString *s = @"tsdfsdfsdfsdf";

        NSData *data = [s dataUsingEncoding:NSUTF8StringEncoding];

        

        //NSData->NSString

        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

        NSLog(@"str:%@",str);

        

        // NSMutableData Variable Data Objects, you can append data

 

 

3. 沙盒 & NSData & NSFileManager

(NSFileManger: create files, copy, delete, cut files (Note: The operating target for the file, not the file contents))

        

/ * ___________________________________ 1. Create a file _____________________________________ * /

        /*

        // Get the current app sandbox directory

        NSString *homePath = NSHomeDirectory();

        

        // additional sub-path

        NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents/file.text"];

 

        // NSFileManager can not be used to create alloc, this class is designed to Singleton

        NSFileManager *fileManager1 = [NSFileManager defaultManager];

        NSFileManager *fileManager2 = [NSFileManager defaultManager];

        NSLog (@ "f1 =% p, f2 =% p", fileManager1, fileManager2); // address of observation, found to be identical

        

        // NSFileManager can only be created by the class method defaultManager

        NSFileManager *fileManager = [NSFileManager defaultManager];

        NSString * string = @ "automated testing department";

        // will NSString into NSData object.

        NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];

        

        // filePath created according to the path corresponding documents Note: You can create a file, you can not create directories (folders).

        BOOL success = [fileManager createFileAtPath:filePath contents:data attributes:nil];

        if (success) {

            NSLog (@ "file is successfully created");

        }else {

            NSLog (@ "file creation failed");

        }

        

        // Create a folder

        NSString *filePath2 = [homePath stringByAppendingPathComponent:@"Documents/demo"];

        NSError *error;

        

        BOOL success2 = [fileManager createDirectoryAtPath:filePath2 withIntermediateDirectories:YES attributes:nil error:&error];

        if (!success2) {

            NSLog (@ "creation failed:% @", error);

        }

        */

        

/ * ___________________________________ 2. _____________________________________ read the file * /

        

        /*

        // Get the current app sandbox root directory

        NSString *homePath = NSHomeDirectory();

        

        // additional sub-path

        NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents/file.text"];

        

        NSFileManager *fileManager = [NSFileManager defaultManager];

        

        // read the data file based on the path

        NSData *data = [fileManager contentsAtPath:filePath];

        

        //NSData 转 NSString

        NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

        NSLog(@"%@",string);

        */

/ * 3 ___________________________________ mobile (leading edge) document ...................................................... * /

        

        /*

        // Get the current app sandbox root directory

        NSString *homePath = NSHomeDirectory();

        

        // source path

        NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents/file.text"];

        

        //Target path

        NSString *targetPath = [homePath stringByAppendingPathComponent:@"Documents/demo/file2.text"];

        

        NSFileManager *fileManager = [NSFileManager defaultManager];

        BOOL success = [fileManager moveItemAtPath:filePath toPath:targetPath error:nil];

        if (!success) {

            NSLog (@ "move failed");

        }

        // a thought: how to achieve to move to this file to change the name ?? Method: by cutting, move the file from the current directory to the current directory

        */

 

/ * ___________________________________ 4. Copy the files _____________________________________ * /

        

        /*

        // Get the current app sandbox directory

        NSString *hoemPath = NSHomeDirectory();

        

        // source path

        NSString *filePath = [hoemPath stringByAppendingPathComponent:@"Documents/demo/file3.text"];

        

        //Target path

        NSString *targetPath = [hoemPath stringByAppendingPathComponent:@"Documents/file.text"];

        NSFileManager *fileManager = [NSFileManager defaultManager];

        

        BOOL success = [fileManager copyItemAtPath:filePath toPath:targetPath error:nil];

        if (!success) {

            

            NSLog (@ "copy failed");

        }

         */

        

/ * ___________________________________ 3. _____________________________________ delete the file * /

        

        /*

        // Get the current app sandbox directory

        NSString *hoemPath = NSHomeDirectory();

        // source path

        NSString *filePath = [hoemPath stringByAppendingPathComponent:@"Documents/demo/file3.text"];

 

        NSFileManager *fileManager = [NSFileManager defaultManager];

        // determine whether a file exists

        BOOL fileExist = [fileManager fileExistsAtPath:filePath];

        

        if (fileExist) {

            // removeItemAtPath: delete the file.

            BOOL success = [fileManager removeItemAtPath:filePath error:nil];

            if (success) {

                NSLog (@ "deleted successfully");

            }

 

         */

        

        

/ * ___________________________________ 4. _____________________________________ get the properties file * /

        

        NSFileManager *fileManager = [NSFileManager defaultManager];

        NSString *homePath = NSHomeDirectory();

        

        //Target path

        NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents/file.text"];

        

        // get the file attributes

        NSDictionary *fileAttr = [fileManager attributesOfItemAtPath:filePath error:nil];

        NSLog(@"%@",fileAttr);

        

        NSNumber *fileSize = [fileAttr objectForKey:NSFileSize];

        long sizeValue = [fileSize longValue];

        NSLog (@ "File size:% ld", sizeValue);

        

        // below to read the file size is not desirable, because all the data in the file into memory, when a large file, too much memory.

        //NSData *data = [fileManager contentsAtPath:filePath];

        //NSInteger len = data.length;

 

 

4. The read-write file & NSFileHandle - Operation File Content

(Attention: NSFileHandle difference NSFileManager (mainly for directory operations), NSFileHandle (main contents of the file operations))

        

/ * _______________________________ NSString read and write files __________________________________________ * /

        

        /*

        //1.NSString write file

        NSString * s = @ "automated testing department";

        

        //file path

        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/filetext"];

        

        // the string to the file

        BOOL success = [s writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];

        

        if (success) {

            NSLog (@ "string successfully written");

        }

 

        //2.NSString read file

        When reading the contents of the file path // create a string while the corresponding file

        NSString *string = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

        NSLog(@"string=%@",string);

        */

        

/ * _______________________________ NSData read and write files __________________________________________ * /

 

        /*

        //1.NSData read file

        //file path

        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/file.text"];

        

        When // Create NSData, while reading the contents of the file

        NSData *data = [[NSData alloc] initWithContentsOfFile:path];

        

        NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

        NSLog(@"%@",string);

        

 

        //2.NSData write file

        //[data writeToFile:<#(nonnull NSString *)#> atomically:<#(BOOL)#>]

        */

        

        /*

         Note: NSArray, NSDictionary can only store NSNumber, NSString, NSData, NSDate, NSArray, NSDictionary

         To successfully written to the file, the file is written to us as the "property list file"

         

         */

        

/ * _______________________________ NSArray read and write files __________________________________________ * /

        

        //1.NSArray write file

        /*

        NSString *s1 = @"zhangsan";

        NSString * s2 = @ "John Doe";

 

        //file path

        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/array.plist"];

        NSLog(@"path:%@",path);

        NSArray *array = [[NSArray alloc] initWithObjects:s1,s2, nil];

        

        BOOL success = [array writeToFile:path atomically:YES];

        

        if (success) {

            

            NSLog (@ "successfully written");

        }

         */

        

        

        // arrays, dictionaries can be deposited into NSNumber, objects other than NSData, NSDate, NSArray, NSDictionary, you can not write to file

        /*

        Person *p = [[Person alloc] init];

        NSArray *array2 = [NSArray arrayWithObjects:p,@"demo", nil];

        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/array2.plist"];

        

        BOOL success2 = [array2 writeToFile:path atomically:YES];

        

        if (!success2) {

            NSLog (@ "write failed");

        }

         */

        

        /*

        //2.NSArray read file

        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/array.plist"];

//        NSString *path1 = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Property List.plist"];

        NSArray *readArray = [[NSArray alloc] initWithContentsOfFile:path];

        

        for (NSString *s in readArray) {

            NSLog(@"s = %@",s);

        }

        */

        

        

/ * _______________________________ NSDictionary read and write files __________________________________________ * /

        

        //1.NSDictionary write to file

        NSDictionary *dic = @{

                                @"name":@"jack",

                                @"birthday":[NSDate date],

                                @"age":@22

                              };

        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/dic.plist"];

        BOOL success = [dic writeToFile:path atomically:YES];

        

        if (success) {

            NSLog (@ "successfully written");

        }

        

        //2.NSDictionary read file

        NSDictionary *readDic = [NSDictionary dictionaryWithContentsOfFile:path];

        NSLog(@"readDic:%@",readDic);

        

 

The additional data and positioning the read

 

/ * _____________________________________ 1. _____________________________________ additional data * /

        

        /*

        NSString *s = @"MLB-AE-SW";

        

        // landed current user's home directory

        NSString *homePath = NSHomeDirectory();

        NSString *path = [homePath stringByAppendingPathComponent:@"file.text"];

        

        // write to file

        [s writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];

        */

        

        /*

        NSString *homePath = NSHomeDirectory();

        

        NSString *path = [homePath stringByAppendingPathComponent:@"file.text"];

        

        // Create a written NSFileHandle objects

        NSFileHandle *writeHandle = [NSFileHandle fileHandleForWritingAtPath:path];

        

        // set the file offset to the end, from end to start writing when writing files

        [writeHandle seekToEndOfFile];

        

        NSString * appendString = @ "additional data";

        NSData *data = [appendString dataUsingEncoding:NSUTF8StringEncoding];

        

        // start writing data from the current offset

        [writeHandle writeData:data];

        

        // close the file

        [writeHandle closeFile];

         */

        

/ * _____________________________________ 2. ...................................................... * positioning the read /

        

        // currently logged in user's home directory

        NSString *homePath = NSHomeDirectory();

        NSString *path = [homePath stringByAppendingPathComponent:@"Documents/file.text"];

        

        // get the file size by NSFileManager

        NSFileManager *fileManager = [NSFileManager defaultManager];

        NSDictionary *fileAttr = [fileManager attributesOfItemAtPath:path error:nil];

        NSNumber *fileSize = [fileAttr objectForKey:NSFileSize];

        long long sizeValue = [fileSize longLongValue];

        

        NSFileHandle readHandle * = [NSFileHandle fileHandleForReadingAtPath: path];

        // the offset is set to an intermediate position

        [ReadHandle seekToFileOffset: sizeValue / 2];

        

        // read from the current file to the end offset

        NSData *data = [readHandle readDataToEndOfFile];

        

        //NSData ---> NSString

        NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

        

        NSLog(@"%@",string);

 

 

6. NSFileHandle realize the function of copying files

 

        NSString *homePath = NSHomeDirectory();

        NSString * srcPath = [homePath stringByAppendingPathComponent: @ "06 Lesson File Manager .pdf"];

        

        // destination file path

        NSString * targetPath = [homePath stringByAppendingPathComponent: @ "Documents / 06 Lesson File Manager .pdf"];

        

        

        /*

         Note: Use only NSFileHandle scriptures to read and write file exists, the file can not be created

             Create a file using NSFileManager

         */

        NSFileManager *fileManager = [NSFileManager defaultManager];

        // create the target file

        BOOL success = [fileManager createFileAtPath:targetPath contents:nil attributes:nil];

        

        if (success) {

            

            NSLog (@ "target file created successfully!");

        }

        

        // Create NSFileHandle object is used to read the file

        NSFileHandle readHandle * = [NSFileHandle fileHandleForReadingAtPath: srcPath];

        

        // Create an object for writing NSFileHandle

        NSFileHandle *writerHande = [NSFileHandle fileHandleForWritingAtPath:targetPath];

        

        

        // read the current offset from the end of the file, the default offset is the starting position

        //NSData *data = [readHandle readDataToEndOfFile];

        // Ibid.

        NSData * data = [readHandle availableData]; // defects: the entire contents of the file is read each time (when the file is large, the program will Crash)

                                                    // solution: a read a few bytes, a section of the reading.

        

        

        // write data to the destination file

        [writerHande writeData:data];

        

        // close the file

        [ReadHandle closeFile];

        [writerHande closeFile];

 

Reproduced in: https: //www.cnblogs.com/share-iOS/p/5816419.html

Guess you like

Origin blog.csdn.net/weixin_30363509/article/details/94799092
Recommended