Read a file in a macOS Command Line Tool project

2019-04-26 20:27发布

问题:

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") }

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?

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.

回答1:

There is no app bundle for a command-line tool. Just a binary.

You need to put the JSON file in a known location (current directory?) and construct the path yourself