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
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,657评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,889评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,057评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,509评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,562评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,443评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,251评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,129评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,561评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,779评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,902评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,621评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,220评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,838评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,971评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,025评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,843评论 2 354

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,325评论 0 10
  • 2018年6月20日 姓名:韩兴国 公司:上海东方星教育 【六项精进打卡第24天】 【知~学习】 《大学》2遍,共...
    韩兴国阅读 106评论 0 0
  • 夏天已经来临,肉肉不可避免的出现褪色和散型现象。但颜值降低只是暂时的,秋天它们就会逆袭,重回巅峰。那么在欣赏不到美...
    LSJ娟lsj阅读 280评论 0 0
  • 一、从间接学习到直接学习 读书的目的,可以是消遣,也可以是自我提升。很明显,题主的目的是要进行自我提升的。那么问题...
    黑色玫瑰d阅读 884评论 0 6