Read a text file line by line in Swift?

前端 未结 6 721
广开言路
广开言路 2020-12-05 04:14

I just started learning Swift. I have got my code to read from the text file, and the App displays the content of the entire text file. How can I display line by line and ca

相关标签:
6条回答
  • 2020-12-05 04:26

    Swift 3.0

    if let path = Bundle.main.path(forResource: "TextFile", ofType: "txt") {
        do {
            let data = try String(contentsOfFile: path, encoding: .utf8)
            let myStrings = data.components(separatedBy: .newlines)
            TextView.text = myStrings.joined(separator: ", ")
        } catch {
            print(error)
        }
    }
    

    The variable myStrings should be each line of the data.

    The code used is from: Reading file line by line in iOS SDK written in Obj-C and using NSString

    Check edit history for previous versions of Swift.

    0 讨论(0)
  • 2020-12-05 04:31

    Swift 5.2

    The solution below shows how to read one line at a time. This is quite different from reading the entire contents into memory. Reading line-by-line scales well if you have a large file to read. Putting an entire file into memory does not scale well for large files.

    The example below uses a while loop that quits when there are no more lines, but you can choose a different number of lines to read if you wish.

    The code works as follows:

    1. create a URL that tells where the file is located
    2. make sure the file exists
    3. open the file for reading
    4. set up some initial variables for reading
    5. read each line using getLine()
    6. close the file when done

    You could make the code less verbose if you wish; I have included comments to explain what the variables' purposes are.

    Swift 5.2

    import Cocoa
    
    // get URL to the the documents directory in the sandbox
    let home = FileManager.default.homeDirectoryForCurrentUser
    
    // add a filename
    let fileUrl = home
        .appendingPathComponent("Documents")
        .appendingPathComponent("my_file")
        .appendingPathExtension("txt")
    
    
    // make sure the file exists
    guard FileManager.default.fileExists(atPath: fileUrl.path) else {
        preconditionFailure("file expected at \(fileUrl.absoluteString) is missing")
    }
    
    // open the file for reading
    // note: user should be prompted the first time to allow reading from this location
    guard let filePointer:UnsafeMutablePointer<FILE> = fopen(fileUrl.path,"r") else {
        preconditionFailure("Could not open file at \(fileUrl.absoluteString)")
    }
    
    // a pointer to a null-terminated, UTF-8 encoded sequence of bytes
    var lineByteArrayPointer: UnsafeMutablePointer<CChar>? = nil
    
    // the smallest multiple of 16 that will fit the byte array for this line
    var lineCap: Int = 0
    
    // initial iteration
    var bytesRead = getline(&lineByteArrayPointer, &lineCap, filePointer)
    
    defer {
        // remember to close the file when done
        fclose(filePointer)
    }
    
    while (bytesRead > 0) {
        
        // note: this translates the sequence of bytes to a string using UTF-8 interpretation
        let lineAsString = String.init(cString:lineByteArrayPointer!)
        
        // do whatever you need to do with this single line of text
        // for debugging, can print it
        print(lineAsString)
        
        // updates number of bytes read, for the next iteration
        bytesRead = getline(&lineByteArrayPointer, &lineCap, filePointer)
    }
    
    0 讨论(0)
  • 2020-12-05 04:39

    This is not pretty, but I believe it works (on Swift 5). This uses the underlying POSIX getline command for iteration and file reading.

    typealias LineState = (
      // pointer to a C string representing a line
      linePtr:UnsafeMutablePointer<CChar>?,
      linecap:Int,
      filePtr:UnsafeMutablePointer<FILE>?
    )
    
    /// Returns a sequence which iterates through all lines of the the file at the URL.
    ///
    /// - Parameter url: file URL of a file to read
    /// - Returns: a Sequence which lazily iterates through lines of the file
    ///
    /// - warning: the caller of this function **must** iterate through all lines of the file, since aborting iteration midway will leak memory and a file pointer
    /// - precondition: the file must be UTF8-encoded (which includes, ASCII-encoded)
    func lines(ofFile url:URL) -> UnfoldSequence<String,LineState>
    {
      let initialState:LineState = (linePtr:nil, linecap:0, filePtr:fopen(fileURL.path,"r"))
      return sequence(state: initialState, next: { (state) -> String? in
        if getline(&state.linePtr, &state.linecap, state.filePtr) > 0,
          let theLine = state.linePtr  {
          return String.init(cString:theLine)
        }
        else {
          if let actualLine = state.linePtr  { free(actualLine) }
          fclose(state.filePtr)
          return nil
        }
      })
    }
    

    Here is how you might use it:

    for line in lines(ofFile:myFileURL) {
      print(line)
    }
    
    0 讨论(0)
  • 2020-12-05 04:39

    Probably the simplest, and easiest way to do this in Swift 5.0, would be the following:

    import Foundation
    
    // Determine the file name
    let filename = "main.swift"
    
    // Read the contents of the specified file
    let contents = try! String(contentsOfFile: filename)
    
    // Split the file into separate lines
    let lines = contents.split(separator:"\n")
    
    // Iterate over each line and print the line
    for line in lines {
        print("\(line)")
    }
    

    Note: This reads the entire file into memory, and then just iterates over the file in memory to produce lines....

    Credit goes to: https://wiki.codermerlin.com/mediawiki/index.php/Code_Snippet:_Print_a_File_Line-by-Line

    0 讨论(0)
  • 2020-12-05 04:41

    You probably do want to read the entire file in at once. I bet it's very small.

    But then you want to split the resulting string into an array, and then distribute the array's contents among various UI elements, such as table cells.

    A simple example:

        var x: String = "abc\ndef"
        var y = x.componentsSeparatedByString("\n")
        // y is now a [String]: ["abc", "def"]
    
    0 讨论(0)
  • 2020-12-05 04:46

    Update for Swift 2.0 / Xcode 7.2

        do {
            if let path = NSBundle.mainBundle().pathForResource("TextFile", ofType: "txt"){
                let data = try String(contentsOfFile:path, encoding: NSUTF8StringEncoding)
    
                let myStrings = data.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
                print(myStrings)
            }
        } catch let err as NSError {
            //do sth with Error
            print(err)
        }
    

    Also worth to mention is that this code reads a file which is in the project folder (since pathForResource is used), and not in e.g. the documents folder of the device

    0 讨论(0)
提交回复
热议问题