读取文档文件夹中的文本文件 – Iphone SDK

我有这个代码如下:

NSString *fileName = [[NSUserDefaults standardUserDefaults] objectForKey:@"recentDownload"]; NSString *fullPath = [NSBundle pathForResource:fileName ofType:@"txt" inDirectory:[NSHomeDirectory() stringByAppendingString:@"/Documents/"]]; NSError *error = nil; [textViewerDownload setText:[NSString stringWithContentsOfFile:fullPath encoding: NSUTF8StringEncoding error:&error]]; 
  • textviewerdownload是显示文件中的文本的文本textview 。 实际的文件名存储在一个名为recentDownload

  • 当我build立这个,我点击下面这个button ,我的应用程序crashes

  • 有什么语法错误或只是简单的错误?

NSBundle类用于在应用程序包中查找事物,但Documents目录位于包之外,所以生成path的方式将不起作用。 试试这个:

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *fullPath = [[paths lastObject] stringByAppendingPathComponent:@"recentDownload.txt"]; 
 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *myPathDocs = [documentsDirectory stringByAppendingPathComponent:@"myfile.txt"]; if (![[NSFileManager defaultManager] fileExistsAtPath:myPathDocs]) { NSString *myPathInfo = [[NSBundle mainBundle] pathForResource:@"myfile" ofType:@"txt"]; NSFileManager *fileManager = [NSFileManager defaultManager]; [fileManager copyItemAtPath:myPathInfo toPath:myPathDocs error:NULL]; } //Load from File NSString *myString = [[NSString alloc] initWithContentsOfFile:myPathDocs encoding:NSUTF8StringEncoding error:NULL]; 

这对我有效

无论如何,谢谢大家

对于从文本文件读取/写入检查此url 。