Application Bundle中讀取檔案
阿新 • • 發佈:2018-12-25
首先必須將檔案加入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;
- }
- }