Object-c: Comparison of two types of file reading and writing

Source: Internet
Author: User

Comparison of Reading and writing methods: (mainly for local read local files)
Mode \ Action Read Write
Non-URL mode

Stringwithcontentsoffile

WriteToFile

Url method

Stringwithcontentsofurl

Writetourl

in actual development, most of them use URL. In the case of a write operation, the contents of the original file are overwritten if the file exists, and if the file does not exist, a new file is created two, non-URL mode 1. The unfamiliar is the file write method, there will be a atomically parameter.                                         Atomically (atomicity): When set to Yes, it is completely revoked (more secure) when it is not finished. When no is set, no end is written and will not be undone.  2.NSError object, you can get the error message by Localizeddescription method. Example:
////main.m//string Exercise 2: Read and write Files////Created by Apple on 15/12/7.//copyright©2015 year Apple. All rights reserved.//#import<Foundation/Foundation.h>voidReadFile (NSString *path);voidWriteToFile (NSString *path, NSString *str);intMainintargcConst Char*argv[]) {    //reading the contents of a file//nsstring *path1 = @ "/users/apple/desktop/keenapps/object-c/object-c-test/string Exercise 2: Read and Write file/1.txt";NSString*path1 =@"/users/apple/desktop/1.txt"; NSLog (@"Read file:");    ReadFile (path1); //Write file ContentsNSString*path2 =@"/users/apple/desktop/keenapps/object-c/object-c-test/String Exercise 2: Read and write Files/2.txt"; NSLog (@"Write File"); NSString*str =@"This is a test";    WriteToFile (PATH2,STR); NSLog (@"Read file:");    ReadFile (path2); return 0;} //Read FilevoidReadFile (NSString *path) {Nserror*error =Nil; NSString*STR = [NSString stringwithcontentsoffile:path encoding:nsutf8stringencoding error:&ERROR]; if(Error! =Nil) {NSLog ([error localizeddescription]);//output the error message to    }    Else{NSLog (@"%@", str); }}//Write FilevoidWriteToFile (NSString *path, NSString *str) {Nserror*error =Nil; //Atomically:yes, when not finished, will be all revoked; no time, not finished, will not be revoked//Note: This write method is created if the file is not present, or if the file exists, overwrite the contents of the original fileBOOL Flag= [str writetofile:path atomically:yes encoding:nsutf8stringencoding error:&error];//General error is set to nil to ensure successful writing    if(flag) {NSLog (@"Write Success"); }    Else{NSLog (@"Write Failed"); }}
URL mode URL method, according to the way the URL object is created, there are two types: I. Create a URL object by URLWithString Method 1) Path: protocol + IP + file path access to local resources: file://+ IP +/file path access network resources:/HTTP + IP +/file path Note: (1) When the local resource is read, the IP address is not written, that is: file:///file path (after the IP address/cannot be omitted, represents the root path)     (2) If you include Chinese in the path, you need to use the stringbyaddingpercentescapesusingencoding method or Stringbyaddingpercentencodingwithallowedcharacters method to encode the path, otherwise, will prompt: Thefile couldn ' t be opened because the Specified URL type isn ' t supported. (URL type not supported)For example:
NSString *path =@"file://192.168.1.103/Users/apple/Desktop/Read and write file Practice 2/1.txt ";//nsstring *path = @"File///users/apple/desktop/Read and write files Practice 2/1.txt ";//path = [path stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];//older method, now replaced by the following methodPath =[path Stringbyaddingpercentencodingwithallowedcharacters:[nscharacterset urlqueryallowedcharacterset]; Nsurl*url =[Nsurl Urlwithstring:path]; NSString*STR = [NSString stringwithcontentsofurl:url encoding:nsutf8stringencoding error:&ERROR];if(Error = =Nil) {NSLog (@"%@", str);}Else{NSLog (@"%@", [Error localizeddescription]);}
Two. Create a URL object from the Fileurlwithpath method to access local resources

When using this method, it is important to note:

1) The system will help us to automatically join the file://, we do not need to add. Add again, the path is wrong.

2) Even if the URL contains Chinese, it can be accessed. The included Chinese will be processed automatically by the system. Therefore, in general development, access to local resources, all use this method.

Example:
@" /users/apple/desktop/Read and write files Practice 2/1.txt "; Nsurl *url = [Nsurl Fileurlwithpath:path]; NSString *str = [NSString stringwithcontentsofurl:url encoding:nsutf8stringencoding error:&error];if (Error = = nil) {    NSLog (@"%@", str);} else{    NSLog (@"%@", [error localizeddescription]);}
Three, comprehensive examples:
////main.m//read and write files Exercise 2////Created by Apple on 15/12/7.//copyright©2015 year Apple. All rights reserved.//#import<Foundation/Foundation.h>intMainintargcConst Char*argv[]) {    //one. File Read//path Use URL//1. Load the local file. Note: file://, not file:///NSString *path =@"file://192.168.1.103/Users/apple/Desktop/KeenApps/Object-C/Object-c-Test/reading and writing files practice 2/1.txt"; //If you are loading a local resource, the host address on the URL is not//Note: The trailing slash after the IP address cannot be omitted! (It represents the path of the following)//Path = @ "File:///users/apple/desktop/keenapps/object-c/object-c-test/Read and write files Practice 2/1.txt "; //If the path contains Chinese, first encode//the consequence of not encoding is: The file couldn ' t be opened because the specified URL type isn ' t supported. (URL type not supported)//path = [path stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];//older method, now replaced by the following method//path = [path Stringbyaddingpercentencodingwithallowedcharacters:[nscharacterset urlqueryallowedcharacterset]]; //2. Load network resources//path = @ "http://www.baidu.com"; //Nsurl *url = [Nsurl Urlwithstring:path]; //3. Use Fileurlwithpath to create the URL object and load the local resource.     /*when using this method, it is important to note that: 1) the system will help us to automatically join the file://, we do not need to add.     Add again, the path is wrong. 2) Even if the URL contains Chinese, it can be accessed. The included Chinese will be processed automatically by the system.     Therefore, in general development, access to local resources, all use this method. */Path=@"/users/apple/desktop/keenapps/object-c/object-c-test/reading and writing files practice 2/1.txt"; Nsurl*url =[Nsurl Fileurlwithpath:path]; Nserror*error =Nil; NSString*STR = [NSString stringwithcontentsofurl:url encoding:nsutf8stringencoding error:&ERROR]; if(Error = =Nil) {NSLog (@"%@", str); }    Else{NSLog (@"%@", [Error localizeddescription]); }    //two. File Write//path Use URLNserror *error2 =Nil; NSString*STR2 =@"This is a test2"; /*//The first way nsstring *path2 [email protected] "file:///Users/apple/Desktop/KeenApps/Object-C/Object-c-Test/read and write files Exercise 2/    2.txt ";    path2 = [path2 stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];    NSLog (@ "path2 =%@", path2);    Nsurl *URL2 = [Nsurl urlwithstring:path2]; */    //The second wayNSString *path2 =@"/users/apple/desktop/keenapps/object-c/object-c-test/reading and writing files practice 2/2.txt"; Nsurl*URL2 =[Nsurl Fileurlwithpath:path2]; //Note: If the file exists, overwrite the contents of the original file, or if the file does not exist, create a new[str2 writetourl:url2 atomically:yes encoding:nsutf8stringencoding error:&Error2]; if(Error2! =Nil) {NSLog (@"%@", [Error2 localizeddescription]); }    Else{NSLog (@"file Write success!"); }    return 0;}

Recommended reading: Http://www.itstrike.cn/Question/0bdc7287-c70a-416b-a013-3914493a599c.html

Object-c: Comparison of two types of file reading and writing

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.