Dartでファイル名を変更

概要

Dartでファイル名を変更するには、dart:ioパッケージを使用する。
ユーザからファイルへのアクセス権限要求を行っている必要がある。

手順

まず、パッケージをインポートする。

import 'dart:io';

次に名前を変更したいファイルのパスを変数に入れる。
ファイルの取得方法 > Dartでファイルを取得する

そしてファイルオブジェクトを作成する。

File file = File(filePath);

renameメソッドを使用して、ファイル名を変更する。

try { 
	// Fileオブジェクトを作成 
	File file = File(filePath); 
	// ファイル名を変更 
	bool success = file.rename(newFileName); 
	if (success) { 
		print('File renamed successfully.'); 
	} else { 
		print('Failed to rename the file.'); 
	} 
} catch (e) { 
	print('Error occurred: $e'); 
}

これで正常に動作すればファイル名が変更されるはずである。