简体   繁体   English

在swift,iOS游乐场中读取文件

[英]Read file in swift, iOS playground

Having searched through the many (many!) swift playground questions to even craft this code, I'm still struggling. 在搜索了许多(很多!)快速游乐场问题甚至制作这些代码后,我仍然在苦苦挣扎。

I've placed a text file in the Resources folder of package contents, and it appears as an alias (link) in the running temp files generated by the playground ( /var/folders/ ... ). 我已经在包内容的Resources文件夹中放置了一个文本文件,它在playground( /var/folders/ ... )生成的运行临时文件中显示为别名(链接)。

import UIKit

let bundle = NSBundle.mainBundle()

let myFilePath = bundle.pathForResource("dict1", ofType: "txt")

println(myFilePath)    // <-- this is correct, there is a shortcut to the Resource file at this location

var error:NSError?

var content = String(contentsOfFile:myFilePath!, encoding:NSUTF8StringEncoding, error: &error)

println(content!)  // <-- this is *NOT* the file contents [EDIT: see later note]

// Demonstrate there's no error
if let theError = error {
    print("\(theError.localizedDescription)")
} else {
    print("No error")
}

The problem being, that content is shown in the playground output as being Some "apple\\ngame\\nhow\\nswift\\ntoken" , rather than the file contents as expected. 问题是,该content在playground输出中显示为Some "apple\\ngame\\nhow\\nswift\\ntoken" ,而不是预期的文件内容。

It's finding the file, because if I change the filename, it errors. 它正在查找文件,因为如果我更改文件名,则会出错。 Any advice on getting the file contents? 有关获取文件内容的任何建议吗?

Xcode 6.1 Xcode 6.1

EDIT: So, the actual problem was that I wasn't expecting the playground output (including, println ) to be escaped. 编辑:所以, 实际的问题是我没想到操场输出(包括, println )被转义。 That, combined with fatigue and other stupidities led me to believe there was a problem, when none existed. 结合疲劳和其他愚蠢行为,让我相信存在问题,如果不存在的话。

Interestingly, not everything seems to be escaped in playground: 有趣的是,并非一切似乎都在操场上逃脱:

println("foo\nbar")    // Outputs "foo\nbar", escaped
println("\\n")         // Outputs "\n", unescaped

You can try creating a class for opening and saving your files: 您可以尝试创建一个用于打开和保存文件的类:

update: Xcode 10 • Swift 4.2 更新: Xcode 10•Swift 4.2

class File {
    class func open(_ path: String, encoding: String.Encoding = .utf8) -> String? {
        if FileManager.default.fileExists(atPath: path) {
            do {
                return try String(contentsOfFile: path, encoding: encoding)
            } catch {
                print(error)
                return nil
            }
        }
        return  nil
    }

    class func save(_ path: String, _ content: String, encoding: String.Encoding = .utf8) -> Bool {
        do {
            try content.write(toFile: path, atomically: true, encoding: encoding)
            return true
        } catch {
            print(error)
            return false
        }
    }
}

usage: File.save 用法:File.save

let stringToSave: String = "Your text"

let didSave = File.save("\(NSHomeDirectory())/Desktop/file.txt", stringToSave) 

if didSave { print("file saved") } else { print("error saving file") } 

usage: File.open 用法:File.open

if let loadedData = File.open("\(NSHomeDirectory())/Desktop/file.txt") {
    print(loadedData)
} else {
    println("error reading file")
 }  

If you prefer working with URL s (as I do and recommended by Apple): 如果您更喜欢使用URL (正如我所做并由Apple推荐):
Note that in Swift 4, the class URL already exists. 请注意 ,在Swift 4中,类URL已存在。

class Url {
    class func open(url: URL) -> String? {
        do {
            return try String(contentsOf: url, encoding: String.Encoding.utf8)
        } catch {
            print(error)
            return nil
        }
    }

    class func save(url: URL, fileContent: String) -> Bool {
        do {
            try fileContent.write(to: url, atomically: true, encoding: .utf8)
            return true
        } catch {
            print(error)
            return false
        }
    }
}

I have seen this problem with .txt files created from .rtf files using TextEdit. 我已经看到使用TextEdit从.rtf文件创建的.txt文件的这个问题。

I loaded a text.txt file in the resources folder of my playground using similar code to you. 我使用类似的代码在我的游乐场的resources文件夹中加载了一个text.txt文件。 The file contents was "hello there" and was made by converting an .rtf file to .txt by changing the extension. 文件内容是“你好”,是通过更改扩展名将.rtf文件转换为.txt。

let path = NSBundle.mainBundle().pathForResource("text", ofType: "txt")//or rtf for an rtf file
var text = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!
println(text)

The output was: 输出是:

{\\rtf1\\ansi\\ansicpg1252\\cocoartf1343\\cocoasubrtf140 {\\fonttbl\\f0\\fswiss\\fcharset0 Helvetica;} {\\colortbl;\\red255\\green255\\blue255;} \\margl1440\\margr1440\\vieww10800\\viewh8400\\viewkind0 \\pard\\tx720\\tx1440\\tx2160\\tx2880\\tx3600\\tx4320\\tx5040\\tx5760\\tx6480\\tx7200\\tx7920\\tx8640\\pardirnatural {\\ rtf1 \\ ansi \\ ansicpg1252 \\ cocoartf1343 \\ cocoasubrtf140 {\\ fonttbl \\ f0 \\ fswiss \\ fcharset0 Helvetica;} {\\ colortbl; \\ red255 \\ green255 \\ blue255;} \\ margl1440 \\ margr1440 \\ vieww10800 \\ viewh8400 \\ viewkind0 \\ pard \\ tx720 \\ tx1440 \\ tx2160 \\ tx2880 \\ tx3600 \\ tx4320 \\ tx5040 \\ tx5760 \\ tx6480 \\ tx7200 \\ tx7920 \\ tx8640 \\ pardirnatural

\\f0\\fs24 \\cf0 hello there} \\ f0 \\ fs24 \\ cf0你好那里}

So the "hello there" is embedded. 所以“你好那里”是嵌入式的。 This is the problem with all the layout information in a .rtf file. 这是.rtf文件中所有布局信息的问题。

I went back to TextEdit and created a true .txt file. 我回到TextEdit并创建了一个真正的.txt文件。 After opening a file - Format|Make Plain Text 打开文件后 - 格式化|制作纯文本

Now this same code gave the console output "hello there". 现在这个相同的代码给控制台输出“你好那里”。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM