文章出處
View Code
View Code
文章列表
用到的是NSString中的initWithContentsOfFile: encoding方法

// // main.m // 讀取指定文件并輸出內容 // // Created by Apple on 15/11/24. // Copyright © 2015年 Apple. All rights reserved. // /* *讀取指定txt文件,并把文件中的內容輸出出來, */ #import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { NSError *error = nil; NSMutableString *path = [NSMutableString stringWithCapacity:42]; NSString *home = [@"~" stringByExpandingTildeInPath]; [path appendString:home]; [path appendString:@"/work/temp.txt"]; //NSString *string = [[NSString alloc] initWithContentsOfFile:@"/Users/apple/work/temp.txt" encoding:NSUTF8StringEncoding error:&error]; NSString *string = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error]; //如果有報錯,則把報錯信息輸出來 if (error != nil) { NSLog(@"%@",[error localizedDescription]); } NSLog(@"%@",string); return 0; }
補充多一個例子:

// // main.m // 字符串練習2:讀寫文件 // // Created by Apple on 15/12/7. // Copyright © 2015年 Apple. All rights reserved. // #import <Foundation/Foundation.h> void readFile(NSString *path); void writeToFile(NSString *path, NSString *str); int main(int argc, const char * argv[]) { //讀取文件中的內容 NSString *path1 = @"/Users/apple/Desktop/KeenApps/Object-C/Object-c-Test/字符串練習2:讀寫文件/1.txt"; //NSString *path = @"/Users/apple/Desktop/2.txt"; NSLog(@"讀取文件:"); readFile(path1); //寫入文件內容 NSString *path2 = @"/Users/apple/Desktop/KeenApps/Object-C/Object-c-Test/字符串練習2:讀寫文件/2.txt"; NSLog(@"寫入文件"); NSString *str = @"這是一個測試"; writeToFile(path2,str); NSLog(@"讀取文件:"); readFile(path2); return 0; } //讀取文件 void readFile(NSString *path){ NSError *error = nil; NSString *str = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error]; if (error != nil) { NSLog([error localizedDescription]);//將錯誤信息輸出來 } else{ NSLog(@"%@",str); } } //寫入文件 void writeToFile(NSString *path, NSString *str){ NSError *error = nil; //atomically : YES時,沒有寫完,則會全部撤銷;NO時候,沒有寫完,不會撤銷 //注意:這種寫入方式,如果文件補存在,則創建;如果文件存在,則覆蓋原文件的內容 BOOL flag = [str writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];//一般error都設置為nil,保證寫入成功 if (flag) { NSLog(@"寫入成功"); } else{ NSLog(@"寫入失敗"); } }
補充:
使用URL方式訪問:http://www.cnblogs.com/KeenLeung/p/5028012.html
文章列表
全站熱搜