06. Reading Strings From and Writing Strings To Files and URLs

从字符串中读取字符串并将字符串写入文件和URL
相关链接:
https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Strings/Articles/readingFiles.html#//apple_ref/doc/uid/TP40003459-SW1

Reading files or URLs using NSString is straightforward provided that you know what encoding the resource uses—if you don't know the encoding, reading a resource is more challenging. When you write to a file or URL, you must specify the encoding to use. (Where possible, you should use URLs because these are more efficient.)

  • 使用NSString读取文件或URL非常简单,前提是您知道资源使用的编码 - 如果您不知道编码,则读取资源更具挑战性。 写入文件或URL时,必须指定要使用的编码。 (如果可能,您应该使用URL,因为这些更有效。)

Reading From Files and URLs

  • 从文件和URL读取

NSString provides a variety of methods to read data from files and URLs. In general, it is much easier to read data if you know its encoding. If you have plain text and no knowledge of the encoding, you are already in a difficult position. You should avoid placing yourself in this position if at all possible—anything that calls for the use of plain text files should specify the encoding (preferably UTF-8 or UTF-16+BOM).

  • NSString提供了多种从文件和URL读取数据的方法。 通常,如果您知道其编码,则更容易读取数据。 如果您有纯文本并且不知道编码,那么您已经处于困境。 如果可能的话,你应该避免将自己置于这个位置 - 任何要求使用纯文本文件的东西都应该指定编码(最好是UTF-8或UTF-16 + BOM)。

Reading data with a known encoding

  • 使用已知编码读取数据

To read from a file or URL for which you know the encoding, you use stringWithContentsOfFile:encoding:error: or stringWithContentsOfURL:encoding:error:, or the corresponding init... method, as illustrated in the following example.

  • 要从您知道编码的文件或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 ...

You can also initialize a string using a data object, as illustrated in the following examples. Again, you must specify the correct encoding.

  • 您还可以使用数据对象初始化字符串,如以下示例所示。 同样,您必须指定正确的编码。
NSURL *URL = ...;
NSData *data = [NSData dataWithContentsOfURL:URL];
 
// Assuming data is in UTF8.
NSString *string = [NSString stringWithUTF8String:[data bytes]];
 
// if data is in another encoding, for example ISO-8859-1
NSString *string = [[NSString alloc]
            initWithData:data encoding: NSISOLatin1StringEncoding];

Reading data with an unknown encoding

  • 使用未知编码读取数据

If you find yourself with text of unknown encoding, it is best to make sure that there is a mechanism for correcting the inevitable errors. For example, Apple's Mail and Safari applications have encoding menus, and TextEdit allows the user to reopen the file with an explicitly specified encoding.

  • 如果您发现自己有未知编码的文本,最好确保有一种机制来纠正不可避免的错误。 例如,Apple的Mail和Safari应用程序具有编码菜单,TextEdit允许用户使用明确指定的编码重新打开文件。

If you are forced to guess the encoding (and note that in the absence of explicit information, it is a guess):

  • 如果您被迫猜测编码(并注意在没有明确信息的情况下,这是猜测):
  1. Try stringWithContentsOfFile:usedEncoding:error: or initWithContentsOfFile:usedEncoding:error: (or the URL-based equivalents).

    • 尝试stringWithContentsOfFile:usedEncoding:error:或initWithContentsOfFile:usedEncoding:error :(或基于URL的等价物)。

    These methods try to determine the encoding of the resource, and if successful return by reference the encoding used.

    • 这些方法尝试确定资源的编码,如果成功通过引用返回所使用的编码。
  2. If (1) fails, try to read the resource by specifying UTF-8 as the encoding.

    • 如果(1)失败,请尝试通过将UTF-8指定为编码来读取资源。
  3. If (2) fails, try an appropriate legacy encoding.

    • 如果(2)失败,请尝试适当的遗留编码。

    "Appropriate" here depends a bit on circumstances; it might be the default C string encoding, it might be ISO or Windows Latin 1, or something else, depending on where your data are coming from.

    • 这里的“适当”取决于具体情况; 它可能是默认的C字符串编码,可能是ISO或Windows Latin 1,或其他东西,具体取决于数据的来源。
  4. Finally, you can try NSAttributedString's loading methods from the Application Kit (such as initWithURL:options:documentAttributes:error:).

    • 最后,您可以从Application Kit尝试NSAttributedString的加载方法(例如initWithURL:options:documentAttributes:error :)。

    These methods attempt to load plain text files, and return the encoding used. They can be used on more-or-less arbitrary text documents, and are worth considering if your application has no special expertise in text. They might not be as appropriate for Foundation-level tools or documents that are not natural-language text.

  • 这些方法尝试加载纯文本文件,并返回使用的编码。 它们可以用于或多或少的任意文本文档,如果您的应用程序没有特殊的文本专业知识,则值得考虑。 它们可能不适合基础级工具或非自然语言文本的文档。

Writing to Files and URLs

Compared with reading data from a file or URL, writing is straightforward—NSString provides two convenient methods, writeToFile:atomically:encoding:error: and writeToURL:atomically:encoding:error:. You must specify the encoding that should be used, and choose whether to write the resource atomically or not. If you do not choose to write atomically, the string is written directly to the path you specify. If you choose to write it atomically, it is written first to an auxiliary file, and then the auxiliary file is renamed to the path. This option guarantees that the file, if it exists at all, won’t be corrupted even if the system should crash during writing. If you write to an URL, the atomicity option is ignored if the destination is not of a type that can be accessed atomically.

  • 与从文件或URL读取数据相比,写入很简单 - NSString提供了两个方便的方法,writeToFile:atomically:encoding:error:和writeToURL:atomically:encoding:error:。 您必须指定应使用的编码,并选择是否以原子方式写入资源。 如果您不选择以原子方式编写,则会将字符串直接写入指定的路径。 如果选择以原子方式编写它,则首先将其写入辅助文件,然后将辅助文件重命名为路径。 此选项可确保文件(如果存在)不会损坏,即使系统在写入期间崩溃也是如此。 如果您写入URL,则如果目标不是可以原子方式访问的类型,则会忽略原子性选项。
NSURL *URL = ...;
NSString *string = ...;
NSError *error;
BOOL ok = [string writeToURL:URL atomically:YES
                  encoding:NSUnicodeStringEncoding error:&error];
if (!ok) {
    // an error occurred
    NSLog(@"Error writing file at %@\n%@",
              path, [error localizedFailureReason]);
    // implementation continues ...
Summary

This table summarizes the most common means of reading and writing string objects to and from files and URLs:

  • 此表总结了在文件和URL中读取和写入字符串对象的最常用方法:


    image.png

你可能感兴趣的:(06. Reading Strings From and Writing Strings To Files and URLs)