如何在Swift命令行应用程序中从文件系统读取文件? [英] How do I read a file from the filesystem in a Swift command line app?

查看:55
本文介绍了如何在Swift命令行应用程序中从文件系统读取文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我才刚刚开始学习Swift,并且要自学,我正在制作一个简单的命令行应用程序.它将最终连接到在线数据源,但最初我想从文件中加载数据.我已经看过各种有关在Swift中读取文件内容的指南,但似乎没有一个对我有用.到目前为止,这是我的应用程序:

I'm just starting learning Swift and to teach myself I'm making a simple command line app. It will eventually connect to an online data source but initially I want to load data from a file. I've seen various guides on reading the contents of a file in Swift but none of them seem to work for me. Here is my app so far:

import Foundation

// Set the file path
let path = "/Users⁩/username/workspace⁩/⁨Swift⁩/sis⁩/sis/data.json⁩"

do {
    // Get the contents
    let contents = try String(contentsOfFile: path, encoding: .utf8)
    print(contents)
}
catch let error as NSError {
    print("Ooops! Something went wrong: \(error)")
}

运行它会输出:

Ooops! Something went wrong: Error Domain=NSCocoaErrorDomain Code=260 "The file "data.json⁩" couldn’t be opened because there is no such file." UserInfo={NSFilePath=/Users⁩/username/workspace⁩/⁨Swift⁩/sis⁩/sis/data.json⁩, NSUnderlyingError=0x100e19a50 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

但是在终端上:

$ ls -l /Users/username/workspace/Swift/sis/sis/data.json
-rwxrwxrwx@ 1 username  staff  165563 16 Jan 17:14 /Users/username/workspace/Swift/sis/sis/data.json

(是的,我以某种方式放宽了权限,以防万一是问题所在)

(yeah I relaxed the permissions somewhat just in case that was the problem)

我注意到的唯一略微异常的事情(除了该文件不存在的不正确断言之外)是,当我将XCode输出的路径复制并粘贴到iTerm2中时,它将在每个路径组件之间放置空格:

The only slightly anomalous thing I noticed (aside from the inaccurate assertion that the file doesn't exist) was that when I copy and past the path from the XCode output into iTerm2 it puts spaces between each path component:

(粘贴为图像,然后将其复制并粘贴回此形式似乎隐藏了空格-仍然可能无关紧要)

(pasted as an image as copying it and pasting it back into this form seems to hide the spaces - this is probably irrelevant anyway)

任何帮助我们弄清楚这一点的人,将不胜感激!

Any help figuring this out would be really appreciated!

推荐答案

我复制了您的代码,下载了

I copied your code, downloaded a sample json file to my desktop, and renamed it to example_ 1.json (I included a space inside the file name).

import Foundation

// Set the file path
let path = "/Users⁩/username/Desktop/example_ 1.json⁩"

do {
    // Get the contents
    let contents = try String(contentsOfFile: path, encoding: .utf8)
    print(contents)
}
catch let error as NSError {
    print("Ooops! Something went wrong: \(error)")
}

它成功打印了文件.当我将内容定义为NSString时,它也起作用.

It successfully printed the file. It also worked when I defined contents as a NSString.

let contents = try NSString(contentsOfFile: path, 
                            encoding: String.Encoding.ascii.rawValue)

我正在使用 Swift 4.2.1

这篇关于如何在Swift命令行应用程序中从文件系统读取文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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