IOS UI distinguish between NSBundle and NSURL (read file write file)
- 2020-05-27 07:15:32
The example of this article is to distinguish NSBundle and NSURL, and the specific implementation content is as follows
Add a file to the project. aa.txt is added in this routine, and the content of the file is baidu: www.baidu.com. Now we need to use NSBundle and NSURL to get the content respectively.
// Read file contents // methods 1: Read by file path NSString *pathBundle = [[NSBundle mainBundle]pathForResource:@"aa" ofType:@"txt"]; NSString *outstringbundle = [NSString stringWithContentsOfFile:pathBundle encoding:NSUTF8StringEncoding error:nil]; // methods 2: In accordance with the URL 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 Sandbox mechanism and The file path [11786:518929] baidu : www.baidu.com //////// baidu : www.baidu.com
Write to file:
First, create a new file:
NSString *newPath = [NSString stringWithFormat:@"%@/Documents/New",NSHomeDirectory()]; // Define the file path and file name first NSString *newfile = [NSString stringWithFormat:@"%@/new.mp3",newPath]; // use createFileAtPath Create a file [[NSFileManager defaultManager]createFileAtPath:newfile contents:nil attributes:nil]; NSLog(@"%@",newPath);
After reading and writing:
// Written to the file // 1 , use first data Read the data NSData *data = [[NSData alloc]initWithContentsOfFile:pathBundle]; NSLog(@"%@",data); // 2 , to read data Write to the sandbox file, newfile Created in the sandbox file above mp3 file [data writeToFile:newfile atomically:YES];
I hope it will be helpful for you to distinguish NSBundle from NSURL through a brief example.