How To Read a File From Your Application Bundle

来源:互联网 发布:yaosir乒乓器材淘宝店 编辑:程序博客网 时间:2024/05/22 12:32

 

First you need to add your file to the Resources folder of your Xcode project. Then you can access the file like this (assuming the file is called MyFile.txt):

  1. NSString *filePath = [[NSBundle mainBundle] pathForResource:@"MyFile" ofType:@"txt"];  
  2. NSData *myData = [NSData dataWithContentsOfFile:filePath];  
  3. if (myData) {  
  4.     // do something useful  
  5. }  

Here’s a complete example reading a help text file into a UIWebView.

  1. NSString *filePath = [[NSBundle mainBundle] pathForResource:@"HelpDoc" ofType:@"htm"];  
  2. NSData *htmlData = [NSData dataWithContentsOfFile:filePath];  
  3. if (htmlData) {  
  4.     [webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@"http://iphoneincubator.com"]];  
  5. }  

If you want to read the file into a string, which you can then display in a UITextView, for example, then do this:

  1. NSString *filePath = [[NSBundle mainBundle] pathForResource:@"important" ofType:@"txt"];  
  2. if (filePath) {  
  3.     NSString *myText = [NSString stringWithContentsOfFile:filePath];  
  4.     if (myText) {  
  5.         textView.text= myText;  
  6.     }  
  7. }  

 

原创粉丝点击