ios 如何在ios中读取文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9189812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to read a text file in ios
提问by Shubham
I am reading a txt file with a very simple code. The problem is that in the Log statments I only get the path of the file but contents are null. I guess that the problem lies in encoding part.Any Suggestions on how to read my text file.
我正在阅读一个非常简单的代码的txt文件。问题是在 Log statments 我只得到文件的路径但内容为空。我猜问题在于编码部分。有关如何阅读我的文本文件的任何建议。
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);
}
回答by iOSPawan
Here encoding parameter is not set properly.
这里的编码参数设置不正确。
Try this
尝试这个
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
NSLog(@"%@",path);
回答by Jayprakash Dubey
Use the following code to read a Text File from Bundle :
使用以下代码从 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);
回答by Stavash
I don't get the encoding you are passing the function "stringWithContentsOfFile". Try passing it "NSUTF8StringEncoding". If this doesn't work, create an NSError instance and pass it by reference to the function.
我没有得到您传递函数“stringWithContentsOfFile”的编码。尝试传递它“NSUTF8StringEncoding”。如果这不起作用,请创建一个 NSError 实例并将其通过引用传递给函数。