16
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Posted at

ファイル読み込み

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()
16
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?