“文件内容"返回零,可能的原因 [英] "contentsOfFile" returning nil, possible cause

查看:34
本文介绍了“文件内容"返回零,可能的原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下在获取 csv 文件的内容时返回 nil.但是,将 csv 表减少到 10 行将正常工作,输出 csv 文件的内容.

The following returns nil when getting the content of a csv file. However, reducing the csv table to 10 rows will work properly, outputting the content of the csv file.

原始 csv 大约有 400,000 个字符,排列在 500 行和 11 列中.什么可能导致它在原始 csv 中返回 nil?

The original csv has about 400,000 characters arranged in 500 rows and 11 columns. What could be causing it to return nil with the original csv?

let dbPath = "/Volumes/Gios2TWD/myDB.csv"

var error: NSError?

let csvContent = NSString(contentsOfFile: dbPath, encoding:NSUTF8StringEncoding, error: &error) as String!

println(csvContent)

println(error)

我正在运行 XCode 版本 6.1 (6A1030)

I'm running XCode Version 6.1 (6A1030)

错误:

可选(错误域=NSCocoaErrorDomain 代码=261无法使用文本编码 Unicode (UTF-8) 打开文件myDB.csv"." UserInfo=0x10050c5b0 {NSFilePath=/Volumes/Gios2TWD/myDB.csv, NSStringEncoding=4})

Optional(Error Domain=NSCocoaErrorDomain Code=261 "The file "myDB.csv" couldn’t be opened using text encoding Unicode (UTF-8)." UserInfo=0x10050c5b0 {NSFilePath=/Volumes/Gios2TWD/myDB.csv, NSStringEncoding=4})

推荐答案

您需要测试以下错误的代码:

You need code that tests for errors something like this:

let dbPath = "/Volumes/Gios2TWD/myDB.csv"
var error: NSError?
let csvContent = NSString(contentsOfFile: dbPath, encoding:NSUTF8StringEncoding, error: &error)
if csvContent != nil {
    // do something with the string
}
else {
    println("error: \(error)")
}

然后尝试理解任何错误消息.如果您需要帮助,请将代码和完整的错误消息发布给 SO.

Then try to understand any error message. Post the code and full error message to SO if you need help.

出现如下错误消息:无法使用文本编码 Unicode (UTF-8) 打开",它不是 UTF-8 文件.文件可能已损坏,或者可能是其他格式.试试 NSMacOSRomanStringEncoding,它是一种非常宽容的 8 位 ASCII 编码.它也可能是另一种 8 位 ASCII 编码.

With an error message like: "couldn’t be opened using text encoding Unicode (UTF-8)" it is not a UTF-8 file. There may be corruption in the file or it many be another format. Try NSMacOSRomanStringEncoding, it is an 8-bit ASCII encoding that is very forgiving. It also might be another 8-bit ASCII encoding.

注意:除非您 100% 确定在任何情况下它们都不会为零,否则不要显式地解包.

Note: Do not explicitly unwrap things unless you are 100% certain that under no circumstances they can never be nil.

这篇关于“文件内容"返回零,可能的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆