2011-08-29 39 views
30

Tôi đã thêm một tệp văn bản vào Xcode, bây giờ tôi muốn tạo một chuỗi với nó. Làm thế nào để tải nó và đặt nó vào một chuỗi?Đọc một tập tin văn bản và biến nó thành một chuỗi

NewsStory1.txt là tệp và tôi đang sử dụng Obj-C.

+0

bản sao có thể có của [Tạo, lưu và đọc tệp văn bản] (http://stackoverflow.com/questions/6123284/create-save-and-read-text-file) –

+1

Tôi 15 khi tôi hỏi điều này câu hỏi. Tôi muốn xóa nó quá tệ. –

+0

https://meta.stackexchange.com/questions/63983/can-i-delete-my-own-question –

Trả lời

65
NSString *path = [[NSBundle mainBundle] pathForResource:@"NewsStory1" ofType:@"txt"]; 
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; 

Xem tài liệu API iOS của Apple cho NSString, đặc biệt là phần "Tạo và khởi tạo một String từ một File"

2

Rất đơn giản

Chỉ cần tạo ra một phương pháp như sau

- (void)customStringFromFile 
{ 
    NSString* filePath = [[NSBundle mainBundle] pathForResource:@"NewsStory1" ofType:@"txt"]; 
    NSString *stringContent = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil]; 
    NSLog(@"\n Result = %@",stringContent); 
} 
5

Trong swift

let path = NSBundle.mainBundle().pathForResource("home", ofType: "html") 

    do { 
     let content = try String(contentsOfFile:path!, encoding: NSUTF8StringEncoding)} catch _ as NSError {} 
Các vấn đề liên quan