text_storage.dart 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import 'dart:convert';
  2. import 'dart:typed_data';
  3. import 'package:fis_common/logger/logger.dart';
  4. import 'package:vitalapp/architecture/storage/file_storage.dart';
  5. /// 文本存储
  6. class TextStorage {
  7. TextStorage({
  8. required this.fileName,
  9. this.directory = "",
  10. });
  11. final String fileName;
  12. final String directory;
  13. FileStorage? _fileStorage;
  14. Future<bool> save(String text) async {
  15. try {
  16. final bytes = Uint8List.fromList(utf8.encode(text));
  17. _fileStorage ??= FileStorage(directory: directory);
  18. final result = await _fileStorage!.save(fileName, bytes);
  19. return result;
  20. } catch (e) {
  21. logger.e("TextStorage save text error.", e);
  22. return false;
  23. }
  24. }
  25. Future<String?> read() async {
  26. _fileStorage ??= FileStorage(directory: directory);
  27. final bytes = await _fileStorage!.read(fileName);
  28. if (bytes == null || bytes.isEmpty) return null;
  29. try {
  30. final str = utf8.decode(bytes);
  31. return str;
  32. } catch (e) {
  33. logger.e("TextStorage convert bytes to string error.", e);
  34. return null;
  35. }
  36. }
  37. Future<bool> delete() async {
  38. try {
  39. _fileStorage ??= FileStorage(directory: directory);
  40. final result = await _fileStorage!.delete(fileName);
  41. return result;
  42. } catch (e) {
  43. logger.e("TextStorage clear error.", e);
  44. return false;
  45. }
  46. }
  47. Future<bool> deleteDirectory() async {
  48. try {
  49. _fileStorage ??= FileStorage(directory: directory);
  50. final result = await _fileStorage!.deleteDirectory(directory);
  51. return result;
  52. } catch (e) {
  53. logger.e("TextStorage clear error.", e);
  54. return false;
  55. }
  56. }
  57. }