我的代码如下:
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
,显示文件中的文字。实际文件名存储在名为NSUserDefault
的{{1}}。
当我构建此内容时,我会点击它所在的recentDownload
和我的应用button
。
语法或简单错误有什么问题吗?
答案 0 :(得分:9)
NSBundle
类用于查找应用程序包中的内容,但Documents目录位于包外,因此生成路径的方式不起作用。试试这个:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *fullPath = [[paths lastObject] stringByAppendingPathComponent:@"recentDownload.txt"];
答案 1 :(得分:6)
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];
这对我有用
无论如何,谢谢大家..
答案 2 :(得分:2)
对于文本文件的读/写,请检查此url。