从文本文件中读取和写入字符串

Jor*_*hez 273 file-io swift

我需要从文本文件中读取和写入数据,但我无法弄清楚如何.

我在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."
Run Code Online (Sandbox Code Playgroud)

Ada*_*dam 502

对于读写,您应该使用可写的位置,例如文档目录.以下代码显示了如何读取和写入简单的字符串.你可以在操场上测试它.

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 */}
}
Run Code Online (Sandbox Code Playgroud)

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 */}
}
Run Code Online (Sandbox Code Playgroud)

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)
}
Run Code Online (Sandbox Code Playgroud)

  • 这应该被删除,代码不适用于新版本的Swift. (6认同)
  • 让 text2 = String.stringWithContentsOfFile(path) // XCode 6.0 (3认同)

wot*_*pal 85

假设您已将文本文件移动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
Run Code Online (Sandbox Code Playgroud)

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

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

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)!
Run Code Online (Sandbox Code Playgroud)

  • 这不再编译在Xcode 8,Swift 3上 (7认同)
  • 对于iOS项目,"stringWithContentsOfFile"不可用(自iOS 7起不推荐使用) (3认同)
  • 你可以使用 String(contentsOfFile: ...) (2认同)

Leo*_*bus 69

Xcode 8.x•Swift 3.x或更高版本

do {
    // get the documents folder url
    if let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
        // create the destination url for the text file to be saved
        let fileURL = documentDirectory.appendingPathComponent("file.txt")
        // define the string/text to be saved
        let text = "Hello World !!!"
        // writing to disk 
        // Note: if you set atomically to true it will overwrite the file if it exists without a warning
        try text.write(to: fileURL, atomically: false, encoding: .utf8)
        print("saving was successful")
        // any posterior code goes here
        // reading from disk
        let savedText = try String(contentsOf: fileURL)
        print("savedText:", savedText)   // "Hello World !!!\n"
    }
} catch {
    print("error:", error)
}
Run Code Online (Sandbox Code Playgroud)


Han*_*son 52

新的更简单和推荐的方法: Apple建议使用URL进行文件处理,上述解决方案似乎已被弃用(请参阅下面的评论).以下是使用URL进行读写的新简单方法(不要忘记处理可能的URL错误):

Swift 4.0和3.1

import Foundation  // Needed for those pasting into Playground

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)")
}
Run Code Online (Sandbox Code Playgroud)

  • @Andrej"URL对象是引用本地文件的首选方式.从文件读取数据或向文件写入数据的大多数对象都有接受NSURL对象而不是路径名作为文件引用的方法." https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/ (5认同)

Cra*_*lot 29

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)")
} 
Run Code Online (Sandbox Code Playgroud)

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

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 ""
    }
    }
Run Code Online (Sandbox Code Playgroud)

例如

let t = "yourFile.txt".contentsOrBlank()
Run Code Online (Sandbox Code Playgroud)

你几乎总是想要一系列的线条:

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

  • 我粘贴了一个方便的扩展@crashalot - 随意删除,欢呼 (2认同)
  • @Alshcompiler 不!您无法将文件写入捆绑包中。 (2认同)

A. *_*lam 11

我只想向您展示第一部分,即阅读.以下是您可以阅读的简单内容:

斯威夫特3:

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

斯威夫特2:

let s = try! String(contentsOfFile: NSBundle.mainBundle().pathForResource("myFile", ofType: "txt")!)
Run Code Online (Sandbox Code Playgroud)


ios*_*ist 5

在Swift> 4.0中读取文件的最简单方法

 let path = Bundle.main.path(forResource: "data", ofType: "txt") // file path for file "data.txt"
        do {
            var text = try String(contentsOfFile: path!)
        }
        catch(_){print("error")}
    }
Run Code Online (Sandbox Code Playgroud)