How to Read a File from The Filesystem in a Swift Command Line App

Read a file in a macOS Command Line Tool project

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

Read and write a String from text file

For reading and writing you should use a location that is writeable, for example documents directory. The following code shows how to read and write a simple string. You can test it on a playground.

Swift 3.x - 5.x

let file = "file.txt" //this is the file. we will write to and read from it

let text = "some text" //just a text

if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {

let fileURL = dir.appendingPathComponent(file)

//writing
do {
try text.write(to: fileURL, atomically: false, encoding: .utf8)
}
catch {/* error handling here */}

//reading
do {
let text2 = try String(contentsOf: fileURL, encoding: .utf8)
}
catch {/* error handling here */}
}

Swift 2.2

let file = "file.txt" //this is the file. we will write to and read from it

let text = "some text" //just a text

if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent(file)

//writing
do {
try text.writeToURL(path, atomically: false, encoding: NSUTF8StringEncoding)
}
catch {/* error handling here */}

//reading
do {
let text2 = try NSString(contentsOfURL: path, encoding: NSUTF8StringEncoding)
}
catch {/* error handling here */}
}

Swift 1.x

let file = "file.txt"

if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] {
let dir = dirs[0] //documents directory
let path = dir.stringByAppendingPathComponent(file);
let text = "some text"

//writing
text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil);

//reading
let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
}

How can I read a file in a swift playground

This works for me. The only thing I changed was to be explicit about the file name (which is implied in your example) - perhaps you have a typo in the off-screen definition of the "file" variable?

let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) as? [String]

let file = "trial.txt" // My change to your code - yours is presumably set off-screen
if let directories = dirs {
let dir = directories[0]; //documents directory
let path = dir.stringByAppendingPathComponent(file);

//read
let content = NSString(contentsOfFile: path, usedEncoding: nil, error: nil)
// works...
}

Update Swift 4.2

As @raistlin points out, this would now be

let dirs = NSSearchPathForDirectoriesInDomains(
FileManager.SearchPathDirectory.documentDirectory,
FileManager.SearchPathDomainMask.userDomainMask,
true)

or, more tersely:

let dirs = NSSearchPathForDirectoriesInDomains(.documentDirectory,
.userDomainMask, true)

Where to place a .txt file and read from it in a IOS project

if let path = Bundle.main.path(forResource: "README", ofType: "txt") {
do {
textView.text = try String(contentsOfFile: path, encoding: .utf8)
} catch let error {
// Handle error here
}
}

Just drop the file anywhere into the project browser and make sure it is added to the right target.

Just to expand on the answer, you can also place them in a folder and use:
+ pathForResource:ofType:inDirectory:.

Browse the files created on a device by the iOS application I'm developing, on workstation?

In Xcode's Organiser, go to your device's Summary tab. Find your application in the list, and click the disclosure triangle. Under it, you should see an icon saying "Application Data". Click the down pointing arrow to download the data, and it'll prompt you for somewhere to save it.

In Xcode 5, listed under your device in Organizer, click on "Applications" and you can see "Data files in Sandbox" in the bottom half of the window.

In Xcode 6, go to Window -> Devices, select the device, select the app name under Installed Apps, click the settings gearbox, then select Download container.... In finder, double finger tap the package and select Show package contents.
Sample Image

How to run terminal command in swift from any directory?

There is a deprecated property currentDirectoryPath on Process.

On the assumption you won't want to use a deprecated property, after reading its documentation head over to the FileManager and look at is provisions for managing the current directory and their implications.

Or just use cd as you've considered – you are launching a shell (zsh) with a shell command line as an argument. A command line can contain multiple commands separated by semicolons so you can prepend a cd to your command value.

The latter approach avoids changing your current process' current directory.

HTH

Reading in a JSON File Using Swift

Follow the below code :

if let path = NSBundle.mainBundle().pathForResource("test", ofType: "json")
{
if let jsonData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)
{
if let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary
{
if let persons : NSArray = jsonResult["person"] as? NSArray
{
// Do stuff
}
}
}
}

The array "persons" will contain all data for key person. Iterate throughs to fetch it.

Swift 4.0:

if let path = Bundle.main.path(forResource: "test", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
if let jsonResult = jsonResult as? Dictionary<String, AnyObject>, let person = jsonResult["person"] as? [Any] {
// do stuff
}
} catch {
// handle error
}
}

How do I catch read/writes to the hard disk and display them on OS X?

Fortunately, I've found how to do this — using Instruments.app (inside of Xcode). You're able to display filesystem operations, which is what I was intending to do.



Related Topics



Leave a reply



Submit