如何将txt文件加载到数组中 [英] How to load a txt file into an array

查看:161
本文介绍了如何将txt文件加载到数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个方法来将txt文件加载到数组中。然而,我不是真的很高兴,因为它看起来非常麻烦,我的初学者的眼睛(我相信我不需要50%的代码),我不知道如何我想如何指定我的txt的确切格式文件,例如NSUTF8StringEncoding。

I coded a method to load a txt file into an array. However, I'm not really happy with it as it looks terribly cumbersome to my beginner's eyes (I'm sure I don't need 50% of my code) and I am somehow wondering how I can specify the exact format of my txt file, e.g. NSUTF8StringEncoding.

这是我的代码:

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
 NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory

 NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Sample.txt"]; 

if (filePath) { // check if file exists - if so load it:
    NSString *myText = [NSString stringWithContentsOfFile:filePath];
    if (myText) {textView.text=myText;}
}

对于如何抛光和指定正确格式的任何建议,我将非常感激。

For any suggestions of how to polish this up and specify the right format, I'd be very grateful.

推荐答案

?你的意思是一个字符串,因为正是你在做什么...

Into an array? You mean into a string, since is exactly what you're doing...

然而,你的代码看起来不错,大多数只是抓住文档

However, your code looks not bad, and most of it is just to grab the documents directory path, and that's not your fault, since it's exactly done this way, according to many knowledge bases.

在编码时,不推荐使用stringWithContentsOfFile,请使用stringWithContentsOfFile: encoding:error:(参见文档)
,您将能够指定正确的编码并获得准确的错误描述。

As of the encoding, stringWithContentsOfFile is deprecated, please use stringWithContentsOfFile:encoding:error: (see the docs) and you will be able to specify the correct encoding and get accurate error descriptions.

这篇关于如何将txt文件加载到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆