I have added a text file to Xcode, now I want to make a string with it.开发者_JS百科 How do I load it and put it into a string?
NewsStory1.txt
is the file, and I'm using Obj-C.
NSString *path = [[NSBundle mainBundle] pathForResource:@"NewsStory1" ofType:@"txt"];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
See Apple's iOS API documentation for NSString, specifically the section "Creating and Initializing a String from a File"
In swift
let path = NSBundle.mainBundle().pathForResource("home", ofType: "html")
do {
let content = try String(contentsOfFile:path!, encoding: NSUTF8StringEncoding)} catch _ as NSError {}
Very Simple
Just create a method as follows
- (void)customStringFromFile
{
NSString* filePath = [[NSBundle mainBundle] pathForResource:@"NewsStory1" ofType:@"txt"];
NSString *stringContent = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"\n Result = %@",stringContent);
}
In Swift 4 this can be done like this:
let path = Bundle.main.path(forResource: "test_data", ofType: "txt")
if let path = path {
do {
let content = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
print(content)
} catch let error as NSError {
print("Error occured: \(error.localizedDescription)")
}
} else {
print("Path not available")
}
Another simpler way with Objective-C:
NSError *error = nil;
NSString *string = [[NSString alloc] initWithContentsOfFile: @"<paht/to/file>"
enconding:NSUTF8StringEncoding
error: &error];
精彩评论