读取文本文件并将其转换为字符串

33 objective-c ios

我已经向Xcode添加了一个文本文件,现在我想用它创建一个字符串.如何加载它并将其放入字符串?

NewsStory1.txt 是文件,我正在使用Obj-C.

Mar*_*era 69

NSString *path = [[NSBundle mainBundle] pathForResource:@"NewsStory1" ofType:@"txt"];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
Run Code Online (Sandbox Code Playgroud)

有关NSString的信息,请参阅Apple的iOS API文档,特别是"从文件创建和初始化字符串"一节


Has*_*ssy 6

在迅速

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

    do {
        let content = try String(contentsOfFile:path!, encoding: NSUTF8StringEncoding)} catch _ as NSError {}
Run Code Online (Sandbox Code Playgroud)


Raj*_*han 5

非常简单

只需创建一个方法如下

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