Swift ファイルやフォルダーをコピーする(copyItem)

FileManager copyItem

FileManagerを使えばファイルやフォルダーのコピーや削除が簡単にできます

let fileManager = FileManager.default
//コピー元指定 : ホームディレクトリのAフォルダー
let atUrl:URL = fileManager.homeDirectoryForCurrentUser.appendingPathComponent("A", isDirectory: true)
//コピー先指定 : /tmp/
let toUrl:URL = URL(fileURLWithPath: "/tmp/A")
do {
    print(atUrl)
    print(toUrl)
    try fileManager.copyItem(at: atUrl, to: toUrl)
} catch {
    print(error.localizedDescription)
}

コピー元は、homeDirectoryForCurrentUser(ホームディレクトリ)のappendingPathComponent()で指定したフォルダー名を指定しました。

コピー先は/tmpですcopyItem()のパラメータはURLなのでコピー元も先もURLになっています

コピー元にフォルダが無い場合は「The file “A” couldn’t be opened because there is no such file.」エラーになります。

copyItem()はフォルダの中にファイルやフォルダが入っていても簡単にコピーできます。

ファイルやフォルダを削除する

削除の場合は、removeItem()を使います。これも同じく引数はURL型です。

import Cocoa

let fileManager = FileManager.default
//削除指定 : /tmp/
let toUrl:URL = URL(fileURLWithPath: "/tmp/A")
do {
    print(toUrl)
    try fileManager.removeItem(at: toUrl)
} catch {
    print(error.localizedDescription)
}

ファイルもフォルダも同じです。フォルダの場合中身があってもサブフォルダがあっても削除できるようです。

2022 MJELD TECHNOLOGIES. ALL RIGHTS RESERVED