2011-08-29 6 views
30

मैंने एक्सकोड में एक टेक्स्ट फ़ाइल जोड़ दी है, अब मैं इसके साथ एक स्ट्रिंग बनाना चाहता हूं। मैं इसे कैसे लोड करूं और इसे एक स्ट्रिंग में डालूं?एक टेक्स्ट फ़ाइल पढ़ना और उसे स्ट्रिंग में बदलना

NewsStory1.txt फ़ाइल है, और मैं ओब्जे-सी का उपयोग कर रहा हूं।

+0

संभावित फ़ाइल [बनाएँ, सहेजें, और पाठ फ़ाइल पढ़ें] के संभावित डुप्लिकेट (http://stackoverflow.com/questions/6123284/create-save-and-read-text-file) –

+1

मैं 15 वर्ष का था जब मैंने यह पूछा सवाल। मैं इसे इतनी बुरी तरह से हटाना चाहता हूं। –

+0

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

उत्तर

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

देखें NSString के लिए एप्पल के आईओएस API दस्तावेज़, विशेष खंड "बनाना और एक फ़ाइल से एक स्ट्रिंग शुरु कर रहा है"

2

बहुत सरल

बस एक विधि बनाने के रूप में

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

स्विफ्ट

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

    do { 
     let content = try String(contentsOfFile:path!, encoding: NSUTF8StringEncoding)} catch _ as NSError {} 
संबंधित मुद्दे