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

rjzwgtxy  于 2023-03-20  发布在  iOS
关注(0)|答案(5)|浏览(150)

我已经在Xcode中添加了一个文本文件,现在我想用它来创建一个字符串。我该如何加载它并将其放入字符串中?
NewsStory1.txt是文件,我使用的是Obj-C。

rpppsulh

rpppsulh1#

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

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

zhte4eai

zhte4eai2#

在斯威夫特

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

    do {
        let content = try String(contentsOfFile:path!, encoding: NSUTF8StringEncoding)} catch _ as NSError {}
0ejtzxu1

0ejtzxu13#

非常简单

只需创建一个方法,如下所示

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

ercv8c1e4#

在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")
}
hc8w905p

hc8w905p5#

Objective-C的另一个简单方法是:

NSError *error = nil;
NSString *string = [[NSString alloc] initWithContentsOfFile: @"<paht/to/file>"
                     enconding:NSUTF8StringEncoding
                     error: &error];

相关问题