Swift - 从指定路径的文件中读取数据

  1. 获取指定路径
var dataArray:[[Substring]] = []
let PathLossTable = "PathLossTable.csv".docConfigDir()
print(PathLossTable)

out:

/Users/joshwang/Documents/App/Resources/PathLossTable.csv

2.获取数据函数;

input:指定文件路径 output:文件中的数据内容

func readPathLossFile(_ path: String) -> [[Substring]]? {
        let fileManager = FileManager.default
        if let url = URL.init(string: path) {
            if fileManager.fileExists(atPath: url.path) {
                let txtData = fileManager.contents(atPath: url.path)
                var dataArray:[[Substring]] = []
                if txtData == nil {
                    return nil
                }
                let readString = String(data: txtData!, encoding: String.Encoding.utf8)
                print("readString: \(String(describing: readString))")
                if readString!.contains("\r\n") {
                    let dataOfRowArray = readString?.split(separator: "\r\n")
                    for (_,rowString) in dataOfRowArray!.enumerated() {
                        let rowArray = rowString.split(separator: ",")
                        if rowArray.count > 0 {
                            dataArray.append(rowArray)
                        }
                    }
                } else {
                    let dataOfRowArray = readString?.split(separator: "\r")
                    for (_,rowString) in dataOfRowArray!.enumerated() {
                        let rowArray = rowString.split(separator: ",")
                        if rowArray.count > 0 {
                            dataArray.append(rowArray)
                        }
                    }
                }
                return dataArray
            }else {
                print("Path loss file is not exists")
                return nil
            }
        }
        return []
    }
//初始化一个二维数组
var dataArray:[[Substring]] = []
//获取需要读取的文件的指定路径
let PathLossTable = "PathLossTable.csv".docConfigDir()
print(PathLossTable)
//调用readPathLossFile()函数读取文件内的数据
dataArray = readPathLossFile(PathLossTable)!
print(dataArray)

out:

/Users/joshwang/Documents/App/Resources/PathLossTable.csv
readString: Optional("Frequency,uplink,downlink,orientation,antenna\r\naaa,bbb,ccc,ddd,eee\r\n111,222,333,444,555")
[["Frequency", "uplink", "downlink", "orientation", "antenna"], ["aaa", "bbb", "ccc", "ddd", "eee"], ["111", "222", "333", "444", "555"]]
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 创作都市 设计师:CSDN官方博客 返回首页