难以打开文本文件

时间:2014-12-11 03:59:10

标签: swift text nstextview

我尝试合并一个允许用户选择文本文件的文件浏览器,并将文件内容显示在NSTextView中。我有文件浏览器工作和文本框工作但我似乎无法打开文件并从中生成至少一个或最好是一系列字符串(每行1个)。

let FileWindow : NSOpenPanel = NSOpenPanel()
    FileWindow.prompt = "Open File"
    FileWindow.title = "Select a File"
    FileWindow.allowedFileTypes = ["txt"]
    FileWindow.canChooseDirectories = false
    FileWindow.allowsMultipleSelection = false
    FileWindow.runModal()
    var selectedfile = FileWindow.URL
    var output = selectedfile?.absoluteString
    var index: String.Index = advance(output!.startIndex, 7)
    FileLabel.stringValue = output!.substringFromIndex(index)

if (selectedfile != nil) {
var data: NSData = NSFileManager.defaultManager().contentsAtPath(output!.substringFromIndex(index))!
        var txt: NSString = NSString(data: data, encoding: NSUTF8StringEncoding)!
        self.FileDisplayView.textStorage?.mutableString.appendString(txt)
        self.FileDisplayView.needsDisplay = true
    }  

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

更新: Xcode 7.1•Swift 2.1

您应该使用String(contentsOfFile :)或String(contentsOfURL:)

创建此类以处理打开的文本文件:

public class File {

    class func open(path: String, encoding: NSStringEncoding = NSUTF8StringEncoding) -> String? {
        guard  NSFileManager().fileExistsAtPath(path) else { return nil }
        do {
            return try String(contentsOfFile: path, encoding: encoding)
        } catch let error as NSError {
            print(error.localizedDescription)
            return nil
        }
    }
    class func save(path: String, fileContent: String, encoding: NSStringEncoding = NSUTF8StringEncoding) -> Bool {
        do {
            try fileContent.writeToFile(path, atomically: true, encoding: encoding)
            return true
        } catch let error as NSError {
            print(error.localizedDescription)
            return false
        }
    }
}

class Url {
    class func read(urL: NSURL, encoding: NSStringEncoding = NSUTF8StringEncoding) -> String? {
        do {
            return try String(contentsOfURL: urL, encoding: encoding)
        } catch let error as NSError {
            print(error.localizedDescription)
            return nil
        }
    }
    class func write(urL: NSURL, fileContent: String, encoding: NSStringEncoding = NSUTF8StringEncoding) -> Bool {
        do {
            try fileContent.writeToURL(urL, atomically: true, encoding: encoding)
            return true
        } catch let error as NSError {
            print(error.localizedDescription)
            return false
        }
    }

}

用法如下:

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

或打开您的网址:

if let loadedString = Url.read(yourUrl) {
    println(loadedString)
} else {
    println("error reading file")
}