fileUtils.dart 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. Future<int> fileSizeOf(path) async {
  24. final file = File(path);
  25. final size = await file.length();
  26. return size;
  27. }
  28. createFolder(String folderPath) async {
  29. // 创建文件夹
  30. final Directory folder = Directory(folderPath);
  31. // 如果文件夹不存在,则创建
  32. if (!await folder.exists()) {
  33. await folder.create();
  34. } else {
  35. Log.d("Folder already exists");
  36. }
  37. }
  38. copyDirectory(Directory source, Directory destination) async {
  39. await for (var entity in source.list(recursive: false)) {
  40. if (entity is Directory) {
  41. var newDirectory = Directory(
  42. path.join(destination.absolute.path, path.basename(entity.path)));
  43. await newDirectory.create();
  44. await copyDirectory(entity.absolute, newDirectory);
  45. } else if (entity is File) {
  46. await entity.copy(
  47. path.join(destination.path, path.basename(entity.path)));
  48. }
  49. }
  50. }
  51. clearDirectory(Directory directory) async {
  52. // 列出所有文件和文件夹
  53. var files = directory.listSync();
  54. // 遍历文件和文件夹
  55. for (var fileEntity in files) {
  56. if (fileEntity is File) {
  57. // 文件直接删除
  58. await fileEntity.delete();
  59. } else if (fileEntity is Directory) {
  60. // 文件夹则递归删除
  61. await clearDirectory(fileEntity);
  62. await fileEntity.delete();
  63. }
  64. }
  65. }
  66. deleteDirectory(String path) async {
  67. final directory = Directory(path);
  68. await directory.delete(recursive: true);
  69. }