我正在尝试从一个文件中获取内容并将其写入另一个文件。我读得很好,但我无法将它写入另一个文件。
我有一个单词数据库。我想根据字母的数量将单词分成不同的文件。所有四个字母的单词都放在一个文件中,依此类推。我在我的资源中添加了一个名为“4letter”的 txt 文件,以下是我的代码:
NSError *error;
//READ
NSString *dbFile = [[NSBundle mainBundle] pathForResource:@"words" ofType:@"txt"];
NSString *test = [NSString stringWithContentsOfFile:dbFile encoding:NSUTF8StringEncoding error:&error];
//convert from string to array
NSArray *lines = [test componentsSeparatedByString:@"\n"];
NSFileHandle *logFile = nil;
logFile = [NSFileHandle fileHandleForWritingAtPath:[[NSBundle mainBundle] pathForResource:@"4letter" ofType:@"txt"]];
//Test if write works
for (int i=0; i<5; i++)
{
NSString *randomAnagram = [[lines objectAtIndex:i] lowercaseString];
[logFile writeData: [randomAnagram dataUsingEncoding: NSNEXTSTEPStringEncoding]];
}
最佳答案
在 iOS 中,您无法写入应用程序包中的文件——整个包都是只读的。请改用 Documents 文件夹的路径。
关于objective-c - 使用 [NSBundle mainBundle] 写入文件失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5853014/