我已经向Xcode添加了一个文本文件,现在我想用它创建一个字符串。如何加载它并将其放入字符串?
NewsStory1.txt
是文件,我正在使用Obj-C。
答案 0 :(得分:69)
NSString *path = [[NSBundle mainBundle] pathForResource:@"NewsStory1" ofType:@"txt"];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
请参阅Apple的NSString的iOS API文档,特别是“从文件创建和初始化字符串”部分
答案 1 :(得分:6)
在swift中
let path = NSBundle.mainBundle().pathForResource("home", ofType: "html")
do {
let content = try String(contentsOfFile:path!, encoding: NSUTF8StringEncoding)} catch _ as NSError {}
答案 2 :(得分:5)
非常简单
只需创建如下方法
- (void)customStringFromFile
{
NSString* filePath = [[NSBundle mainBundle] pathForResource:@"NewsStory1" ofType:@"txt"];
NSString *stringContent = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"\n Result = %@",stringContent);
}
答案 3 :(得分:0)
在Swift 4中,可以这样操作:
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")
}