fileUtil.dart 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import 'dart:io';
  2. import 'package:path/path.dart' as path;
  3. import 'logger.dart';
  4. String fileOrDirectoryName(FileSystemEntity directory) {
  5. return lastNameOfPath(directory.path);
  6. }
  7. String lastNameOfPath(path) {
  8. final paths = path.split(Platform.pathSeparator);
  9. return paths.last;
  10. }
  11. bool isDirectory(path) {
  12. return FileSystemEntity.isDirectorySync(path);
  13. }
  14. Future<bool> isDirectoryExists(path) {
  15. return Directory(path).exists();
  16. }
  17. Future<bool> isFileExists(path) {
  18. return File(path).exists();
  19. }
  20. bool isFile(path) {
  21. return FileSystemEntity.isFileSync(path);
  22. }
  23. createFolder(String folderPath) async {
  24. // 创建文件夹
  25. final Directory folder = Directory(folderPath);
  26. // 如果文件夹不存在,则创建
  27. if (!await folder.exists()) {
  28. await folder.create();
  29. } else {
  30. Log.d("Folder already exists");
  31. }
  32. }
  33. copyDirectory(Directory source, Directory destination) async {
  34. await for (var entity in source.list(recursive: false)) {
  35. if (entity is Directory) {
  36. var newDirectory = Directory(
  37. path.join(destination.absolute.path, path.basename(entity.path)));
  38. await newDirectory.create();
  39. await copyDirectory(entity.absolute, newDirectory);
  40. } else if (entity is File) {
  41. await entity.copy(
  42. path.join(destination.path, path.basename(entity.path)));
  43. }
  44. }
  45. }
  46. clearDirectory(Directory directory) async {
  47. // 列出所有文件和文件夹
  48. var files = directory.listSync();
  49. // 遍历文件和文件夹
  50. for (var fileEntity in files) {
  51. if (fileEntity is File) {
  52. // 文件直接删除
  53. await fileEntity.delete();
  54. } else if (fileEntity is Directory) {
  55. // 文件夹则递归删除
  56. await clearDirectory(fileEntity);
  57. await fileEntity.delete();
  58. }
  59. }
  60. }
  61. deleteDirectory(String path) async {
  62. final directory = Directory(path);
  63. await directory.delete(recursive: true);
  64. }