Read and write a String from text file

前端 未结 21 1472
别跟我提以往
别跟我提以往 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:34

    Assuming that you have moved your text file data.txt to your Xcode-project (Use drag'n'drop and check "Copy files if necessary") you can do the following just like in 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
    

    Update:
    For reading a file from Bundle (iOS) you can use:

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

    Update for 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)!
    

    For 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)
    

提交回复
热议问题