Leer y escribir una cadena desde un archivo de texto

Resuelto Jorge Vega Sánchez asked hace 10 años • 21 respuestas

Necesito leer y escribir datos desde/hacia un archivo de texto, pero no he podido descubrir cómo.

Encontré este código de muestra en el iBook de Swift, pero todavía no sé cómo escribir o leer datos.

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."
Jorge Vega Sánchez avatar Jun 07 '14 20:06 Jorge Vega Sánchez
Aceptado

Para leer y escribir, debe utilizar una ubicación en la que se pueda escribir, por ejemplo, el directorio de documentos. El siguiente código muestra cómo leer y escribir una cadena simple. Puedes probarlo en un parque infantil.

Rápido 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 */}
}

Rápido 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 */}
}

Rápido 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)
}
Adam avatar Jun 07 '2014 14:06 Adam

Suponiendo que ha movido su archivo de texto data.txta su proyecto Xcode (use arrastrar y soltar y marque "Copiar archivos si es necesario"), puede hacer lo siguiente como en 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

Actualización:
para leer un archivo de Bundle (iOS) puede usar:

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

Actualización para 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)!

Para rápido 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)
Dennis Zoma avatar Jun 07 '2014 14:06 Dennis Zoma

Nuevo método más simple y recomendado: Apple recomienda usar URL para el manejo de archivos y las otras soluciones aquí parecen obsoletas (consulte los comentarios a continuación). La siguiente es la nueva forma sencilla de leer y escribir con URL:

Rápido 5+, 4 y 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)

guard let fileURL = dir?.appendingPathComponent(fileName).appendingPathExtension("txt") else {
    fatalError("Not able to create URL")
}
    
// Writing to the file named Test
let outString = "Write this text to the file"
do {
    try outString.write(to: fileURL, atomically: true, encoding: .utf8)
} catch {
    assertionFailure("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
}
    
// Reading it back from the file
var inString = ""
do {
    inString = try String(contentsOf: fileURL)
} catch {
    assertionFailure("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
}
print("Read from the file: \(inString)")
Sverrisson avatar Feb 13 '2016 01:02 Sverrisson

Xcode 8.x • Swift 3.x o posterior

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)
}
Leo Dabus avatar Oct 25 '2014 00:10 Leo Dabus

Xcode 8, Swift 3 formas de leer archivos del paquete de aplicaciones:

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

Aquí hay una extensión conveniente para copiar y pegar

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

Por ejemplo

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

Casi siempre querrás una serie de líneas:

let r:[String] = "yourFile.txt"
     .contentsOrBlank()
     .characters
     .split(separator: "\n", omittingEmptySubsequences:ignore)
     .map(String.init)
Crashalot avatar Sep 24 '2016 08:09 Crashalot