xcode Swift - 读取文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27301034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:18:54  来源:igfitidea点击:

Swift - Read Files

xcodefileswift

提问by Andy

I have a problem with reading a file using swift. I have searched a lot on the web to se if i can find anything, I found 3 different, but I can't get any of them to work

我在使用 swift 读取文件时遇到问题。我在网上搜索了很多,看看我是否能找到任何东西,我发现了 3 个不同的,但我无法让它们中的任何一个工作

here they are :

他们来了 :

    import Foundation


//----- 1 ------
var error: NSErrorPointer = nil

let url = NSURL(string: "ISO.csv")
let csvString = String(contentsOfURL:url!, encoding: NSUTF8StringEncoding, error: error);


println("contest")
println(csvString)


//----- 2 ------
func readFile(fileName: String, fileType: String) -> String{
    var fileRoot = NSBundle.mainBundle().pathForResource(fileName, ofType: fileType)
    var contents = NSString.stringWithContentsOfFile(fileRoot!, encoding: NSUTF8StringEncoding, error: nil)
    return contents
}

// example: read file.txt
var contents = readFile("ISO", "csv")
println(contents)


//----- 3 -----

let path = NSBundle.mainBundle().pathForResource("ISO", ofType: "csv")
var data = String.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: nil)

in number 1 : it just returns a nil. but it works with returning data from a website

在数字 1 中:它只返回一个零。但它适用于从网站返回数据

number 2: /ISO/main.swift:26:20: 'String.Type' does not have a member named 'stringWithContentsOfFile'

2号: /ISO/main.swift:26:20: 'String.Type' does not have a member named 'stringWithContentsOfFile'

number 3 : /ISO/main.swift:38:21: 'stringWithContentsOfFile(_:encoding:error:)' is unavailable: use object construction 'NSString(contentsOfFile:encoding:error:)'

3 号: /ISO/main.swift:38:21: 'stringWithContentsOfFile(_:encoding:error:)' is unavailable: use object construction 'NSString(contentsOfFile:encoding:error:)'

i have no idea what to do, and hoped some of you knew, thanks in advance

我不知道该怎么做,希望你们中的一些人知道,在此先感谢

回答by Bono Lv

Swift 3.0 version:

斯威夫特 3.0 版本:

let path = Bundle.main.url(forResource: FileNameWithoutExtension, withExtension: FileExtension) 
do {
            let content = try String(contentsOf: path!, encoding: .utf8)
            print(content)
} catch  {
            print("Error:file content can't be loaded")
}

回答by Hyman

//----- 2 ------
func readFile(fileName: String, fileType: String) -> String{
    var fileRoot = NSBundle.mainBundle().pathForResource(fileName, ofType: fileType)
    var contents = NSString.stringWithContentsOfFile(fileRoot!, encoding: NSUTF8StringEncoding, error: nil)
    return contents
}

// example: read file.txt
var contents = readFile("ISO", "csv")
println(contents)


//----- 3 -----

let path = NSBundle.mainBundle().pathForResource("ISO", ofType: "csv")
var data = String.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: nil)

Both of these are using the wrong intializer syntax, as the error states. They also do the same exact thing.

正如错误所述,这两个都使用了错误的初始化器语法。他们也做同样的事情。

Fix:

使固定:

let path = NSBundle.mainBundle().pathForResource("ISO", ofType: "csv")
var data = String(contentsOfFile:path, encoding: NSUTF8StringEncoding, error: nil)

回答by shoumikhin

You may find this tool useful: https://github.com/shoumikhin/StreamScanner

你可能会发现这个工具很有用:https: //github.com/shoumikhin/StreamScanner

So to parse your file you do:

因此,要解析您的文件,您可以:

import StreamScanner

if let input = NSFileHandle(forReadingAtPath: NSBundle.mainBundle().pathForResource("ISO", ofType: "csv"))
{
    let scanner = StreamScanner(source: input, delimiters: NSCharacterSet(charactersInString: ",\n"))

    //EITHER

    while
        let field: String = scanner.read() //read CSV field by field, skipping newlines
    {
        //work with field
    }

    //OR

    while  //parse each line at a time (if you're sure there're enough fields in each line and you even know their types)
        let field1: String = scanner.read(),
        let field2: Int = scanner.read(),
        let field3: Double = scanner.read(),
        {
            //work with fields
        }
}

Hope, this helps.

希望这可以帮助。