在objective-c中读取文本文件
我有一个由多个单词组成的文本文件。它们都被新线隔开 我试过的:在objective-c中读取文本文件,objective-c,ios,cocoa-touch,Objective C,Ios,Cocoa Touch,我有一个由多个单词组成的文本文件。它们都被新线隔开 我试过的: NSString *filePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"txt"]; if (filePath) { // This does trigger, so the file is actually found. NSArray *arr = [filePath componentsSeparatedByString:@"\n"]
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"txt"];
if (filePath) { // This does trigger, so the file is actually found.
NSArray *arr = [filePath componentsSeparatedByString:@"\n"];
}
我也试过:
NSMutableArray * lines = [[NSMutableArray alloc] initWithArray:[filePath componentsSeparatedByString:@"\n"] copyItems: YES];
这两种方法似乎都不起作用,因为我只有在使用NSLog读取行时才能获得文件路径。你们谁能帮忙
lines数组似乎只包含一个对象,即文本文件位置的字符串
我想要一个数组,其中每个字符串都是一个字符串,由织物中的一行分隔。您在那里所做的一切都是对文件路径进行黑客攻击-您没有从文件中加载任何数据
有很多方法可以做到这一点<代码>[NSData INITWITH CONTENTS OFURL…可能是一个开始首先,您需要在应用程序包中获取该文件。这意味着您必须将其放入应用程序的“资源”文件夹中 然后你可以这样读:
NSString* path = [[NSBundle mainBundle] pathForResource:@"filename"
ofType:@"txt"];
然后将内容加载到NSString
中就更容易了:
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
然后创建阵列:
NSArray *arr = [content componentsSeparatedByString:@"\n"]; //might also be @"\r" check both.
方法[NSString componentsSeparatedByString:]用于字符串本身,即在您的情况下是文件路径,而不是此路径下的文件内容
有很多方法可以读取文件。Dave DeLong提出了一种解决此问题的聪明方法。请检查。NSString*stringFileContent=[NSString stringWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:@“txt”]类型的@“yourfilename”编码:NSUTF8StringEncoding错误:&错误]您忘了添加“按行分隔”部分,但我自己添加了。现在效果很好。谢谢!请您更正我的答案,以便对其他人也有帮助…谢谢…欢迎使用堆栈溢出!这并不是问题的答案。一旦您有足够的答案,您将能够;相反。