file_storage.dart 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import 'dart:io';
  2. import 'dart:typed_data';
  3. import 'package:path_provider/path_provider.dart';
  4. /// 文件存储
  5. class FileStorage {
  6. FileStorage({
  7. required this.directory,
  8. });
  9. /// 存储目录
  10. final String directory;
  11. Future<Uint8List?> read(String fileName) async {
  12. final storagePath = await _getStoragePath();
  13. final filePath = "$storagePath/$fileName";
  14. final file = File(filePath);
  15. if (!await file.exists()) return null;
  16. final text = await file.readAsBytes();
  17. return text;
  18. }
  19. Future<bool> save(String fileName, Uint8List file) async {
  20. final storagePath = await _getStoragePath();
  21. final filePath = "$storagePath/$fileName";
  22. File fileToSave = File(filePath);
  23. _checkAndCreateDir(storagePath);
  24. if (!await fileToSave.exists()) {
  25. try {
  26. fileToSave = await fileToSave.create(recursive: true);
  27. } catch (e) {
  28. print(e);
  29. }
  30. }
  31. await fileToSave.writeAsBytes(file.toList());
  32. return true;
  33. }
  34. Future<bool> delete(String fileName) async {
  35. final storagePath = await _getStoragePath();
  36. final filePath = "$storagePath/$fileName";
  37. final file = File(filePath);
  38. if (await file.exists()) {
  39. try {
  40. await file.delete();
  41. return true;
  42. } catch (e) {
  43. print(e);
  44. return false;
  45. }
  46. }
  47. return false;
  48. }
  49. Future<bool> deleteDirectory(String directoryPath) async {
  50. final storagePath = await _getStoragePath();
  51. final directory = Directory(storagePath);
  52. final result = await directory.exists();
  53. if (result) {
  54. try {
  55. await directory.delete(recursive: true);
  56. return true;
  57. } catch (e) {
  58. print(e);
  59. return false;
  60. }
  61. }
  62. return false;
  63. }
  64. Future<void> _checkAndCreateDir(String dir) async {
  65. final directory = Directory(dir);
  66. final parentDirectory = directory.parent;
  67. try {
  68. if (!await parentDirectory.exists()) {
  69. await parentDirectory.create(recursive: true);
  70. }
  71. } catch (e) {
  72. print(e);
  73. }
  74. if (!await directory.exists()) {
  75. try {
  76. await directory.create();
  77. } catch (e) {
  78. print(e);
  79. }
  80. }
  81. }
  82. Future<String> _getStoragePath() async {
  83. Directory? dir;
  84. if (Platform.isAndroid) {
  85. dir = await getExternalStorageDirectory();
  86. }
  87. dir ??= await getApplicationDocumentsDirectory();
  88. if (directory.isNotEmpty) {
  89. return "${dir.path}/$directory";
  90. }
  91. return dir.path;
  92. }
  93. }