从文本文件中读取和写入字符串
从文本文件中读取和写入字符串
我需要读写文本文件的数据,但我一直没有弄清楚如何操作。
我在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."
admin 更改状态以发布 2023年5月22日
假设你已经把文本文件data.txt
移动到Xcode项目中(使用拖放并选中"必要时复制文件"),你可以像在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") // file path for file "data.txt" var text = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!
对于Swift 5
let path = Bundle.main.path(forResource: "ListAlertJson", ofType: "txt") // file path for file "data.txt" let string = try String(contentsOfFile: path!, encoding: String.Encoding.utf8)
为了读写,应该使用可写的位置,例如文档目录。下面的代码展示了如何读写一个简单的字符串。你可以在 playground 上测试它。
Swift 3.x - 5.x
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 */} }
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 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) }