在iPhone中如何從Application Bundle中讀取文件
作者:佚名
本文介紹的是在iPhone中如何從Application Bundle中讀取文件,文章以代碼實現,先來看內容。
在iPhone中如何從Application Bundle中讀取文件死本文要介紹的內容,本文是代碼實現結果。先來看內容詳解。首先必須將文件加入Xcode工程的Resources目錄。然后可以如下訪問文件,假設文件為MyFile.txt:
Java代碼
- NSString *filePath = [[NSBundle mainBundle] pathForResource:@"MyFile" ofType:@"txt"];
- NSData *myData = [NSData dataWithContentsOfFile:filePath];
- if (myData) {
- // do something useful
- }
- NSString *filePath = [[NSBundle mainBundle] pathForResource:@"MyFile" ofType:@"txt"];
- NSData *myData = [NSData dataWithContentsOfFile:filePath];
- if (myData) {
- // do something useful
- }
一段將help文本文件讀入UIWebView的完整示例:
Java代碼
- NSString *filePath = [[NSBundle mainBundle] pathForResource:@"HelpDoc" ofType:@"htm"];
- NSData *htmlData = [NSData dataWithContentsOfFile:filePath];
- if (htmlData) {
- [webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@"http://iphoneincubator.com"]];
- }
- NSString *filePath = [[NSBundle mainBundle] pathForResource:@"HelpDoc" ofType:@"htm"];
- NSData *htmlData = [NSData dataWithContentsOfFile:filePath];
- if (htmlData) {
- [webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@"http://iphoneincubator.com"]];
- }
如果想將文件讀入字符串,則可以用UITextView顯示,例如:
Java代碼
- NSString *filePath = [[NSBundle mainBundle] pathForResource:@"important" ofType:@"txt"];
- if (filePath) {
- NSString *myText = [NSString stringWithContentsOfFile:filePath];
- if (myText) {
- textView.text= myText;
- }
- }
- NSString *filePath = [[NSBundle mainBundle] pathForResource:@"important" ofType:@"txt"];
- if (filePath) {
- NSString *myText = [NSString stringWithContentsOfFile:filePath];
- if (myText) {
- textView.text= myText;
- }
- }
小結:在iPhone中如何從Application Bundle中讀取文件的內容介紹完了希望本文對你有所幫助!
責任編輯:zhaolei
來源:
互聯網