LoginSignup
0
1

Swiftでファイルのリネーム

Last updated at Posted at 2023-10-23

URL操作をよく忘れるのでメモしておきます。

ファイルのリネーム

atがリネームしたいファイルのURLで、newFileNameが新しいファイル名(拡張子含)です。

extension FileManager{
    func rename(at:URL,newFileName:String)throws{
        try self.moveItem(at: at, to: at.deletingLastPathComponent().appendingPathComponent(newFileName))
    }
}

moveItemを呼んでファイル移動によってファイル名を変更します。
deletingLastPathComponentは、URL(at)からファイル名(拡張子含)を削除します。
削除した後にappendingPathComponentで新しいファイル名を追加します。

例 ファイル名にアンダースコア(_)をつける

例えばapple.txtを_apple.txtに。

//
//oldStoreURLは適当なURL
//
let fileManager = FileManager.default

do{
    try fileManager.rename(at: oldStoreURL,newFileName: "_" + oldStoreURL.lastPathComponent)
}catch{
    print("リネームエラー \(error)")
}

lastPathComponentはそのURLのファイル名です。

0
1
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
0
1