在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中读取文件的内容介绍完了希望本文对你有所帮助!