Read and write a String from text file

前端 未结 21 1926
别跟我提以往
别跟我提以往 2020-11-22 00:02

I need to read and write data to/from a text file, but I haven\'t been able to figure out how.

I found this sample code in the Swift\'s iBook, but I still don\'t kno

21条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 00:49

    You may find this tool useful to not only read from file in Swift but also parse your input: https://github.com/shoumikhin/StreamScanner

    Just specify the file path and data delimiters like this:

    import StreamScanner
    
    if let input = NSFileHandle(forReadingAtPath: "/file/path")
    {
        let scanner = StreamScanner(source: input, delimiters: NSCharacterSet(charactersInString: ":\n"))  //separate data by colons and newlines
    
        while let field: String = scanner.read()
        {
            //use field
        }
    }
    

    Hope, this helps.

提交回复
热议问题