读取和写入文本文件中的数据

我需要从文本文件中读取/写入数据,但是我一直无法弄清楚。

我在Swift的iBook中发现了这个示例代码,但我仍然不知道如何写入或读取数据。

import Cocoa class DataImporter { /* DataImporter is a class to import data from an external file. The class is assumed to take a non-trivial amount of time to initialize. */ var fileName = "data.txt" // the DataImporter class would provide data importing functionality here } class DataManager { @lazy var importer = DataImporter() var data = String[]() // the DataManager class would provide data management functionality here } let manager = DataManager() manager.data += "Some data" manager.data += "Some more data" // the DataImporter instance for the importer property has not yet been created” println(manager.importer.fileName) // the DataImporter instance for the importer property has now been created // prints "data.txt” var str = "Hello World in Swift Language." 

对于阅读和写作你应该使用可写的位置,例如文档目录。 以下代码显示了如何读取和写入一个简单的string。 你可以在操场上testing它。

Swift 1.x

 let file = "file.txt" if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] { let dir = dirs[0] //documents directory let path = dir.stringByAppendingPathComponent(file); let text = "some text" //writing text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil); //reading let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) } 

Swift 2.2

 let file = "file.txt" //this is the file. we will write to and read from it let text = "some text" //just a text if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first { let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent(file) //writing do { try text.writeToURL(path, atomically: false, encoding: NSUTF8StringEncoding) } catch {/* error handling here */} //reading do { let text2 = try NSString(contentsOfURL: path, encoding: NSUTF8StringEncoding) } catch {/* error handling here */} } 

Swift 3.x和Swift 4.0

 let file = "file.txt" //this is the file. we will write to and read from it let text = "some text" //just a text if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first { let fileURL = dir.appendingPathComponent(file) //writing do { try text.write(to: fileURL, atomically: false, encoding: .utf8) } catch {/* error handling here */} //reading do { let text2 = try String(contentsOf: fileURL, encoding: .utf8) } catch {/* error handling here */} } 

Xcode 8.3.2•Swift 3.1

 // get the documents folder url let documentDirectory = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) // create the destination url for the text file to be saved let fileURL = documentDirectory.appendingPathComponent("file.txt") let text = "some text" do { // writing to disk try text.write(to: fileURL, atomically: false, encoding: .utf8) // saving was successful. any code posterior code goes here // reading from disk do { let mytext = try String(contentsOf: fileURL) print(mytext) // "some text\n" } catch { print("error loading contents of:", fileURL, error) } } catch { print("error writing to url:", fileURL, error) } 

假设你已经将你的文本文件data.txt移动到你的Xcode项目中(使用drag'n'drop并选中“如果需要复制文件”),你可以像Objective-C一样执行以下操作:

 let bundle = NSBundle.mainBundle() let path = bundle.pathForResource("data", ofType: "txt") let content = NSString.stringWithContentsOfFile(path) as String println(content) // prints the content of data.txt 

更新:
要从Bundle(iOS)中读取文件,您可以使用:

 let path = NSBundle.mainBundle().pathForResource("FileName", ofType: "txt") var text = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)! println(text) 

Swift 3的更新:

 let path = Bundle.main.path(forResource: "Data", ofType: "txt") var text = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)! 

新的更简单和推荐的方法:苹果公司build议使用URL进行文件处理,上述解决scheme似乎不赞成(见下面的注释)。 以下是读取和写入URL的新的简单方法(不要忘记处理可能的URL错误):

Swift 4.0和3.1

 let fileName = "Test" let dir = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) // If the directory was found, we write a file to it and read it back if let fileURL = dir?.appendingPathComponent(fileName).appendingPathExtension("txt") { // Write to the file named Test let outString = "Write this text to the file" do { try outString.write(to: fileURL, atomically: true, encoding: .utf8) } catch { print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription) } // Then reading it back from the file var inString = "" do { inString = try String(contentsOf: fileURL) } catch { print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription) } print("Read from the file: \(inString)") } 

Xcode 8,Swift 3从应用程序包中读取文件的方法:

 if let path = Bundle.main.path(forResource: filename, ofType: nil) { do { let text = try String(contentsOfFile: path, encoding: String.Encoding.utf8) print(text) } catch { printError("Failed to read text from \(filename)") } } else { printError("Failed to load file from app bundle \(filename)") } 

这是一个方便的复制和粘贴扩展

 public extension String { func contentsOrBlank()->String { if let path = Bundle.main.path(forResource:self , ofType: nil) { do { let text = try String(contentsOfFile:path, encoding: String.Encoding.utf8) return text } catch { print("Failed to read text from bundle file \(self)") } } else { print("Failed to load file from bundle \(self)") } return "" } } 

例如

 let t = "yourFile.txt".contentsOrBlank() 

你几乎总是想要一些行:

 let r:[String] = "yourFile.txt" .contentsOrBlank() .characters .split(separator: "\n", omittingEmptySubsequences:ignore) .map(String.init) 

我只想告诉你只有第一部分,这是阅读 。 以下是您可以阅读的简单方法:

Swift 3:

 let s = try String(contentsOfFile: Bundle.main.path(forResource: "myFile", ofType: "txt")!) 

Swift 2:

 let s = try! String(contentsOfFile: NSBundle.mainBundle().pathForResource("myFile", ofType: "txt")!) 

目前从Adam接受的答案对我来说有一些错误,但这是我如何重写他的答案,并为我做了这个工作。

 let file = "file.txt" let dirs: [String]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] if (dirs != nil) { let directories:[String] = dirs! let dirs = directories[0]; //documents directory let path = dirs.stringByAppendingPathComponent(file); let text = "some text" //writing text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil); //reading var error:NSError? //reading let text2 = String(contentsOfFile: path, encoding:NSUTF8StringEncoding, error: &error) if let theError = error { print("\(theError.localizedDescription)") } } 

你可能会发现这个工具不仅可以从Swift中读取文件,而且可以parsing你的input: https : //github.com/shoumikhin/StreamScanner

只需指定文件path和数据分隔符,如下所示:

 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 } } 

希望这可以帮助。

我不得不这样重新编码:

 let path = NSBundle.mainBundle().pathForResource("Output_5", ofType: "xml") let text = try? NSString(contentsOfFile: path! as String, encoding: NSUTF8StringEncoding) print(text) 

在函数示例中,具有一些函数包装器的(读写)DocumentsFromFile(…)当然似乎是有意义的,因为OSx和iOS中的所有东西似乎都需要三个或四个主实例化的类和一堆属性,configuration,链接,实例化和设置,只是为了在一个文件中写182个国家的“嗨”。

但是,这些例子还不够完整,无法在真正的程序中使用。 写入function不报告创build或写入文件的任何错误。 在读,我不认为这是一个好主意,返回一个错误,该文件不存在作为应该包含读取的数据的string。 你会想知道它失败了,为什么,通过某种通知机制,像一个例外。 然后,您可以编写一些代码来输出问题所在,并允许用户更正该问题,或者“正确”地在此处中断程序。

你不希望只返回一个string,其中“错误文件不存在”。 然后,你将不得不每次从调用函数的string中查找错误,并在那里处理它。 你也可能无法确定错误string是从实际文件中读取的,还是从代码中生成的。

你甚至不能在swift 2.2和Xcode 7.3中调用这样的读取,因为NSString(contentsOfFile …)抛出一个exception。 如果您没有任何代码来捕获它并对其执行某些操作(如将其打印到标准输出或更好的错误popup窗口或标准错误),那么这是一个编译时错误。 我听说苹果公司正在摆脱try catch和exception,但是这将是一个漫长的过程,没有这个就不可能编写代码。 我不知道&error参数来自哪里,也许是一个老版本,但是NSString.writeTo [File | URL]目前没有NSError参数。 它们在NSString.h中是这样定义的:

 public func writeToURL(url: NSURL, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws public func writeToFile(path: String, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws public convenience init(contentsOfURL url: NSURL, encoding enc: UInt) throws public convenience init(contentsOfFile path: String, encoding enc: UInt) throws 

此外,不存在的文件只是您的程序可能读取文件的许多潜在问题之一,例如权限问题,文件大小,或许多您甚至不想尝试编写处理程序的其他问题他们每个人。 最好是假定它是完全正确的,并在出现问题时抓住并印刷或处理exception情况,此外,在这一点上,你还没有真正的select。

这是我的重写:

 func writeToDocumentsFile(fileName:String,value:String) { let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString! let path = documentsPath.stringByAppendingPathComponent(fileName) do { try value.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding) } catch let error as NSError { print("ERROR : writing to file \(path) : \(error.localizedDescription)") } } func readFromDocumentsFile(fileName:String) -> String { let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString let path = documentsPath.stringByAppendingPathComponent(fileName) var readText : String = "" do { try readText = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String } catch let error as NSError { print("ERROR : reading from file \(fileName) : \(error.localizedDescription)") } return readText } 

对于我的txt文件这样工作:

 let myFileURL = NSBundle.mainBundle().URLForResource("listacomuni", withExtension: "txt")! let myText = try! String(contentsOfURL: myFileURL, encoding: NSISOLatin1StringEncoding) print(String(myText)) 

为了避免混淆和增加容易性,我创build了两个函数来读取和写入string到文件目录中的文件。 这里是function:

 func writeToDocumentsFile(fileName:String,value:String) { let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString let path = documentsPath.stringByAppendingPathComponent(fileName) var error:NSError? value.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding, error: &error) } func readFromDocumentsFile(fileName:String) -> String { let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString let path = documentsPath.stringByAppendingPathComponent(fileName) var checkValidation = NSFileManager.defaultManager() var error:NSError? var file:String if checkValidation.fileExistsAtPath(path) { file = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) as! String } else { file = "*ERROR* \(fileName) does not exist." } return file } 

这里是他们使用的一个例子:

 writeToDocumentsFile("MyText.txt","Hello world!") let value = readFromDocumentsFile("MyText.txt") println(value) //Would output 'Hello world!' let otherValue = readFromDocumentsFile("SomeText.txt") println(otherValue) //Would output '*ERROR* SomeText.txt does not exist.' 

希望这可以帮助!

Xcode版本:6.3.2

写在ViewDidLoad

 var error: NSError? var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) var documentsDirectory = paths.first as String var dataPath = documentsDirectory.stringByAppendingPathComponent("MyFolder") if !NSFileManager.defaultManager().fileExistsAtPath(dataPath) { NSFileManager.defaultManager().createDirectoryAtPath(dataPath, withIntermediateDirectories: false, attributes: nil, error: &error) } else { println("not creted or exist") } func listDocumentDirectoryfiles() -> [String] { if let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as? String { let myFilePath = documentDirectory.stringByAppendingPathComponent("MyFolder") return NSFileManager.defaultManager().contentsOfDirectoryAtPath(myFilePath, error: nil) as [String] } return [] } 

最新的swift3代码
您可以从文本文件中读取数据,只需使用波纹pipe代码这是我的文本文件

  { "NumberOfSlices": "8", "NrScenes": "5", "Scenes": [{ "dataType": "label1", "image":"http://is3.mzstatic.com/image/thumb/Purple19/v4/6e/81/31/6e8131cf-2092-3cd3-534c-28e129897ca9/mzl.syvaewyp.png/53x53bb-85.png", "value": "Hello", "color": "(UIColor.red)" }, { "dataType": "label2", "image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/6c/4c/c1/6c4cc1bc-8f94-7b13-f3aa-84c41443caf3/mzl.hcqvmrix.png/53x53bb-85.png", "value": "Hi There", "color": "(UIColor.blue)" }, { "dataType": "label3", "image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/6c/4c/c1/6c4cc1bc-8f94-7b13-f3aa-84c41443caf3/mzl.hcqvmrix.png/53x53bb-85.png", "value": "hi how ru ", "color": "(UIColor.green)" }, { "dataType": "label4", "image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/6c/4c/c1/6c4cc1bc-8f94-7b13-f3aa-84c41443caf3/mzl.hcqvmrix.png/53x53bb-85.png", "value": "what are u doing ", "color": "(UIColor.purple)" }, { "dataType": "label5", "image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/6c/4c/c1/6c4cc1bc-8f94-7b13-f3aa-84c41443caf3/mzl.hcqvmrix.png/53x53bb-85.png", "value": "how many times ", "color": "(UIColor.white)" }, { "dataType": "label6", "image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/5a/f3/06/5af306b0-7cac-1808-f440-bab7a0d18ec0/mzl.towjvmpm.png/53x53bb-85.png", "value": "hi how ru ", "color": "(UIColor.blue)" }, { "dataType": "label7", "image":"http://is5.mzstatic.com/image/thumb/Purple71/v4/a8/dc/eb/a8dceb29-6daf-ca0f-d037-df9f34cdc476/mzl.ukhhsxik.png/53x53bb-85.png", "value": "hi how ru ", "color": "(UIColor.gry)" }, { "dataType": "label8", "image":"http://is2.mzstatic.com/image/thumb/Purple71/v4/15/23/e0/1523e03c-fff2-291e-80a7-73f35d45c7e5/mzl.zejcvahm.png/53x53bb-85.png", "value": "hi how ru ", "color": "(UIColor.brown)" }] 

}

你可以使用这个代码从swift3中的文本json文件中获取数据

  let filePath = Bundle.main.path(forResource: "nameoftheyourjsonTextfile", ofType: "json") let contentData = FileManager.default.contents(atPath: filePath!) let content = NSString(data: contentData!, encoding: String.Encoding.utf8.rawValue) as? String print(content) let json = try! JSONSerialization.jsonObject(with: contentData!) as! NSDictionary print(json) let app = json.object(forKey: "Scenes") as! NSArray! let _ : NSDictionary for dict in app! { let colorNam = (dict as AnyObject).object(forKey: "color") as! String print("colors are \(colorNam)") // let colour = UIColor(hexString: colorNam) { // colorsArray.append(colour.cgColor) // colorsArray.append(colorNam as! UIColor) let value = (dict as AnyObject).object(forKey: "value") as! String print("the values are \(value)") valuesArray.append(value) let images = (dict as AnyObject).object(forKey: "image") as! String let url = URL(string: images as String) let data = try? Data(contentsOf: url!) print(data) let image1 = UIImage(data: data!)! as UIImage imagesArray.append(image1) print(image1) } 
  func writeToDocumentsFile(fileName:String,value:String) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString let path = documentsPath.appendingPathComponent(fileName) do{ try value.write(toFile: path, atomically: true, encoding: String.Encoding.utf8) }catch{ } } func readFromDocumentsFile(fileName:String) -> String { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString let path = documentsPath.appendingPathComponent(fileName) let checkValidation = FileManager.default var file:String if checkValidation.fileExists(atPath: path) { do{ try file = NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String }catch{ file = "" } } else { file = "" } return file } 

这适用于Linux上的Swift 3.1.1:

 import Foundation let s = try! String(contentsOfFile: "yo", encoding: .utf8) 

Xcode 8.3.2 Swift 3.x。 使用NSKeyedArchiver和NSKeyedUnarchiver

从文件中读取文件

 let documentsDirectoryPathString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let documentsDirectoryPath = NSURL(string: documentsDirectoryPathString)! let jsonFilePath = documentsDirectoryPath.appendingPathComponent("Filename.json") let fileManager = FileManager.default var isDirectory: ObjCBool = false if fileManager.fileExists(atPath: (jsonFilePath?.absoluteString)!, isDirectory: &isDirectory) { let finalDataDict = NSKeyedUnarchiver.unarchiveObject(withFile: (jsonFilePath?.absoluteString)!) as! [String: Any] } else{ print("File does not exists") } 

写文件到文件

 NSKeyedArchiver.archiveRootObject(finalDataDict, toFile:(jsonFilePath?.absoluteString)!)