The example of this article distinguishes NSBundle and Nsurl, and realizes the following contents
In the project to add a file, this routine is added to the Aa.txt, the contents of the file for Baidu: Www.baidu.com, now to use NSBundle and Nsurl respectively to get content, the code is as follows:
read the contents of the file
// Method 1: Read
nsstring *pathbundle by file path = [[NSBundle mainbundle]pathforresource:@ ' AA ' OfType : @ "TXT"];
NSString *outstringbundle = [NSString stringwithcontentsoffile:pathbundle encoding:nsutf8stringencoding Error:nil]; Method 2: Follow the URL to read
nsurl *pathurl = [[NSBundle mainbundle]urlforresource:@ ' AA ' withextension:@ ' txt ' subdirectory : nil];
NSString *outstringurl = [NSString stringwithcontentsofurl:pathurl encoding:nsutf8stringencoding Error:nil];
NSLog (@ "%@\n////////\n%@", Outstringbundle,outstringurl);
The output results are as follows:
2016-03-30 14:48:02.939 sand box mechanism and file path [11,786:518,929] Baidu: www.baidu.com
////////
Baidu: www.baidu.com
Write to File:
Create a new file first:
NSString *newpath = [NSString stringwithformat:@ "%@/documents/new", Nshomedirectory ()]; First, the file path and filename are defined well
nsstring *newfile = [NSString stringwithformat:@ "%@/new.mp3", NewPath]; Create a file using Createfileatpath
[[Nsfilemanager defaultmanager]createfileatpath:newfile Contents:nil attributes : nil];
NSLog (@ "%@", NewPath);
After reading and writing:
write to file
// 1, first read data
nsdata *data = [[NSData alloc]initwithcontentsoffile:pathbundle];
NSLog (@ "%@", data); 2. Writes the read data to the sandbox file, newfile the mp3 file
[data writetofile:newfile Atomically:yes] created in the sandbox file above;
Through a brief example for everyone to distinguish NSBundle and nsurl, I hope to help you learn.