Caution

お使いのブラウザはJavaScriptが実行できない状態になっております。
当サイトはWebプログラミングの情報サイトの為、
JavaScriptが実行できない環境では正しいコンテンツが提供出来ません。
JavaScriptが実行可能な状態でご閲覧頂くようお願い申し上げます。

Swift辞典

FileManager

Swiftの『FileManager』クラスを使うと、ファイルシステムのファイルやディレクトリの作成・確認・削除・移動などの操作が行えます。

メソッド一覧
メソッド / プロパティ概要
FileManager.default共有の FileManager インスタンスを返します。
fileExists(atPath:)指定したパスにファイルまたはディレクトリが存在するか確認します。
createDirectory(at:withIntermediateDirectories:)ディレクトリを作成します。
createFile(atPath:contents:)ファイルを作成してデータを書き込みます。
contentsOfDirectory(at:includingPropertiesForKeys:)ディレクトリ内のファイル一覧を取得します。
copyItem(at:to:)ファイルまたはディレクトリをコピーします。
moveItem(at:to:)ファイルまたはディレクトリを移動します。
removeItem(at:)ファイルまたはディレクトリを削除します。
urls(for:in:)Documents・Caches などの標準ディレクトリの URL を取得します。
サンプルコード
import Foundation

let fm = FileManager.default

// Documents ディレクトリの URL を取得
let docsURL = fm.urls(for: .documentDirectory, in: .userDomainMask)[0]
print("Documents: \(docsURL.path)")

// ファイルの作成と書き込み
let fileURL = docsURL.appendingPathComponent("test.txt")
let content = "Hello, Swift FileManager!"
try? content.write(to: fileURL, atomically: true, encoding: .utf8)

// ファイルの存在確認
print("存在: \(fm.fileExists(atPath: fileURL.path))")

// ファイルの読み込み
if let text = try? String(contentsOf: fileURL, encoding: .utf8) {
    print("内容: \(text)")
}

// ディレクトリの作成
let dirURL = docsURL.appendingPathComponent("MyFolder")
try? fm.createDirectory(at: dirURL, withIntermediateDirectories: true)
print("ディレクトリ作成: \(fm.fileExists(atPath: dirURL.path))")

// ファイルのコピー
let copyURL = dirURL.appendingPathComponent("copy.txt")
try? fm.copyItem(at: fileURL, to: copyURL)

// ディレクトリ内のファイル一覧
if let contents = try? fm.contentsOfDirectory(at: docsURL, includingPropertiesForKeys: nil) {
    print("Documents の内容:")
    for url in contents {
        print("  \(url.lastPathComponent)")
    }
}

// ファイルの移動
let movedURL = docsURL.appendingPathComponent("moved.txt")
try? fm.moveItem(at: copyURL, to: movedURL)

// ファイルの削除
try? fm.removeItem(at: movedURL)
try? fm.removeItem(at: dirURL)
print("削除後の存在: \(fm.fileExists(atPath: movedURL.path))")
概要

iOS・macOS アプリでは、ユーザーのデータを Documents ディレクトリに、キャッシュを Caches ディレクトリに保存するのが慣例です。これらのパスは『FileManager.default.urls(for:in:)』で取得します。

ファイルの読み書きには『String.write(to:)』や『Data.write(to:)』が簡便です。大きなファイルや複雑な操作には FileManager を使います。ファイル操作のエラーは try-catch で適切に処理してください。特に iCloud Drive の同期状態によっては一時的に失敗することがあります。

UserDefaults による小さなデータの永続化についてはUserDefaultsを参照してください。

記事の間違いや著作権の侵害等ございましたらお手数ですがまでご連絡頂ければ幸いです。