Skip to content

Reading Strings From and Writing Strings To Files and URLs

binism edited this page Mar 15, 2016 · 11 revisions

Reading Strings From and Writing Strings To Files and URLs

文件和URLs(统一资源定位器)中字符串的读写

使用NSString对文件和URL进行读取,你只需要简单地指明资源使用的是什么编码————如果你不知道文件的编码,读取它将会是一个很大的挑战。当你写一个文件或URL时,必须指定写入的编码格式。(尽可能地使用URL,因为写URL是相对高效的)。

文件和URLs的读取

NSString 提供多种方法来从文件和URL中读取数据。一般来说,如果你知道文件的编码格式,读取它将会变得更容易。只有文本而不知道它的编码格式,读取将会十分困难。你应该尽量避免这种情况————所有文本读写操作应该指定编码格式(最好使用UTF-8或UTF-16+BOM)。

从已知编码格式的文件中读取数据

从已知编码格式的文件和URL中读取,可以使用stringWithContentsOfFile:encoding:error:或stringWithContentsOfURL:encoding:error:或者相应的init...方法,就像下面的例子中使用的:

NSURL *URL = ...;
NSError *error;
NSString *stringFromFileAtURL = [[NSString alloc]
                                      initWithContentsOfURL:URL
                                      encoding:NSUTF8StringEncoding
                                      error:&error];
if (stringFromFileAtURL == nil) {
    // an error occurred
    NSLog(@"Error reading file at %@\n%@",
              URL, [error localizedFailureReason]);
    // implementation continues ...

Clone this wiki locally