ios 读取文档文件夹中的文本文件 - Iphone SDK
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2709705/
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
Read Text File in Document Folder - Iphone SDK
提问by lab12
I have this code below:
我在下面有这个代码:
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
is thetextview
displaying the text from the file. The actual file name is stored in anNSUserDefault
calledrecentDownload
.When I build this, I click the
button
which this is under, and my applicationcrashes
.Is there anything wrong with the syntax or just simple error?
textviewerdownload
是textview
显示文件中的文本。实际文件名存储在一个NSUserDefault
被调用的recentDownload
.当我构建它时,我单击
button
它下面的 ,然后我的应用程序crashes
.语法有什么问题还是只是简单的错误?
回答by jlehr
The NSBundle
class is used for finding things within your applications bundle, but the Documents directory is outside the bundle, so the way you're generating the path won't work. Try this instead:
在NSBundle
类用于在应用程序中找到的东西捆绑,但文件目录是包外,所以这样你正在生成的路径将无法正常工作。试试这个:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *fullPath = [[paths lastObject] stringByAppendingPathComponent:@"recentDownload.txt"];
回答by iOS
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];
This worked for me
这对我有用
Anyway, thank you all..
不管怎样,谢谢大家。。