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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:10:06  来源:igfitidea点击:

Read Text File in Document Folder - Iphone SDK

iosiphoneobjective-ccocoadocuments

提问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]];
  • textviewerdownloadis the textviewdisplaying the text from the file. The actual file name is stored in an NSUserDefaultcalled recentDownload.

  • When I build this, I click the buttonwhich this is under, and my application crashes.

  • Is there anything wrong with the syntax or just simple error?

  • textviewerdownloadtextview显示文件中的文本。实际文件名存储在一个NSUserDefault被调用的recentDownload.

  • 当我构建它时,我单击button它下面的 ,然后我的应用程序crashes.

  • 语法有什么问题还是只是简单的错误?

回答by jlehr

The NSBundleclass 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..

不管怎样,谢谢大家。。

回答by KingofHeaven

For read/write from text file check this url.

对于从文本文件读/写检查这个url