如何在ios中读取文本文件

Shu*_*ham 13 iphone ios

我正在阅读一个带有非常简单代码的txt文件.问题是在Log状态中我只获取文件的路径但内容为null.我想问题在于编码part.Any关于如何阅读我的文本文件的建议.

NSStringEncoding encoding;
NSString* content;
NSString* path = [[NSBundle mainBundle] pathForResource:@"colorpalette" ofType:@"txt"];
if(path)
{                                               
content = [NSString stringWithContentsOfFile:path  usedEncoding:&encoding  error:NULL];
}
NSLog(@"path is %@",path);
if (content)
{
    NSLog(@" content of file is %@",content);
}
Run Code Online (Sandbox Code Playgroud)

iOS*_*wan 15

此处编码参数未正确设置.

试试这个

NSString* content = [NSString stringWithContentsOfFile:path
                                              encoding:NSUTF8StringEncoding
                                                 error:NULL];
NSLog(@"%@",path);
Run Code Online (Sandbox Code Playgroud)


Jay*_*bey 6

使用以下代码从Bundle中读取文本文件:

NSError *error;
NSString *strFileContent = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]
    pathForResource: @"FileName" ofType: @"txt"] encoding:NSUTF8StringEncoding error:&error];

if(error) {  //Handle error

}

NSLog(@"File content : %@ ", strFileContent);
Run Code Online (Sandbox Code Playgroud)