zoukankan      html  css  js  c++  java
  • Swift3.0语言教程字符串与文件的数据转换

    Swift3.0语言教程字符串与文件的数据转换

    Swift3.0语言教程字符串与文件的数据转换,如果想要对字符串中的字符进行永久保存,可以将字符串中的字符写入到文件中。当然,开发者也可以将写入的内容进行读取,并转换为字符串。首先我们来看如何将字符串中的字符写入到文件中,要想实现此功能,需要使用到NSString中的write(toFile:atomically:encoding:)方法,其语法形式如下:

    func write(toFile path: String, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws

    其中,参数说明如下:

    • path:用来指定写入到文件的路径。
    • useAuxiliaryFile:用来指定是否先将字符串写入到辅助文档。
    • enc:用来指定编码格式。

    【示例1-100】以下将字符串中的字符写入到File空文件中。

    import Foundation

    var str=NSString(string:"All things are difficult before they are easy.")

    var path="/Users/mac/Desktop/File"

    //写入

    do{

       try str.write(toFile: path, atomically: true, encoding: String.Encoding.ascii.rawValue)

    }catch{

       

    }

    运行效果如图1.1所示。

     

    图1.1  运行效果

    在此程序中我们提到了空文件,此文件的创建需要实现以下几步:

    (1)在Xcode的菜单中选择“Flie|New|File…”命令,弹出Choose a template for your new file:对话框,如图1.2所示。

     

    图1.2  Choose a template for your new file:对话框

    (2)选择macOS的Other中的Empty模板,单击Next按钮,弹出文件保存位置对话框,如图1.3所示。

     

    图1.3  文件保存位置对话框

    (3)输入文件名称,选择好文件保存的位置后,单击Create按钮,此时一个File空文件就创建好了,如图1.4所示。

     

    图1.4  File文件

    通过NSString可以将字符串中的字符写入到指定文件中,还可以将文件中的内容读取出来。读取文件内容需要使用到NSString中的的init(contentsOfFile:encoding:)方法,其语法形式如下:

    convenience init(contentsOfFile path: String, encoding enc: UInt) throws

    其中,path用来指定需要读取文件的路径,enc用来指定编码格式。

    【示例1-101】以下将读取文件File中的内容。

    import Foundation

    var path="/Users/mac/Desktop/File"

    var str:NSString?=nil

    //读取文件内容

    do{

     str=try NSString(contentsOfFile: path,encoding: String.Encoding.ascii.rawValue)

    }catch{

       

    }

    print(str!)

    运行结果如下:

    All things are difficult before they are easy.

    Swift3.0语言教程字符串与文件的数据转换

    相关阅读:Swift3.0语言教程字符串转换为数字值

  • 相关阅读:
    linux c dlopen加载动态链接库
    c++锁 测试 (gcc test.cpp -o test -lpthread)
    shell 清理目录下 超过一段时间的数据。
    大话存储学习笔记
    python总结
    正则表达式使用
    #linux shell#模拟日志生成过程
    深入理解Java虚拟机
    Nginx修改access.log日志时间格式
    mfcs100d.lib(dllmodul.obj) : error LNK2005: _DllMain@12 already defined
  • 原文地址:https://www.cnblogs.com/daxueba-ITdaren/p/6077678.html
Copyright © 2011-2022 走看看