在macOS命令行工具项目中读取文件 [英] Read a file in a macOS Command Line Tool project
问题描述
我已经在我的macOS命令行工具项目中添加了一些JSON文件,但似乎无法以通常的方式找到它们。
I've added a few JSON files to my macOS Command Line Tool project, but I can't seem to find them the usual way.
if let path = Bundle.main.path(forResource: "Data", ofType: "json")
{
if let contents = try? String(contentsOfFile: path)
{
print (contents)
}
else { print("Could not load contents of file") }
}
else { print("Could not find path") }
此代码在一个基于View的应用程序,但始终在命令行工具中显示找不到路径。
This code works absolutely fine when used in a View based application, but always prints "Could not find path" in the command line tool.
有人知道我在做什么吗?
Does anyone know what I'm doing wrong?
PS:完全意识到我应该为此使用 guard
语句,但是代码不在函数中,只是让人迷惑不解
P.S: Fully aware that I should be using guard
statements for this, but the code isn't in a function, just faffing about in main.swift till I figure this out.
推荐答案
没有用于命令行工具的应用包。只是二进制文件。
There is no app bundle for a command-line tool. Just a binary.
您需要将JSON文件放在已知位置(当前目录?)并自己构建路径
You need to put the JSON file in a known location (current directory?) and construct the path yourself
这篇关于在macOS命令行工具项目中读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!