Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

[Swift5] もう迷わないファイル入出力

More than 1 year has passed since last update.

ファイル読み込み

import Foundation

let fileName = "hoge.txt"

// ファイルを読み込みモードで開く
let file = FileHandle(forReadingAtPath: fileName)!

// 内容を読み込む(Dataが得られる)
let contentData = file.readDataToEndOfFile()

// Data->Stringに変換
let contentString = String(data: contentData, encoding: .utf8)!

// ファイルを閉じる
file.closeFile()

ファイル書き込み(追記)

import Foundation

let fileName = "hoge.txt"
let contentString = "testContent"

// ファイルを書き込みモードで開く(ファイルの内容は消えない)
let file = FileHandle(forWritingAtPath: fileName)!

// String->Dataに変換
let contentData = contentString.data(using: .utf8)!

// 一番うしろにシーク
file.seekToEndOfFile()

// Dataを書き込み
file.write(contentData)

// ファイルを閉じる
file.closeFile()
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away