Flutter

flutter path_provider操作

2021-11-24  本文已影响0人  流星阁

本次主要实现文件/文件夹的创建、删除、写入、读取具体代码如下:

1.在pubsec.ymal引入"path_provider: ^2.0.7"

path_provider: ^2.0.7

2.废话不多说,直接上代码(注意同步异步问题即可)

import 'package:flutter/cupertino.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';

class Fileutil {
  static Fileutil shared = Fileutil._instance();
  Fileutil._instance();
   ///getExternalStorageDirectory():获取存储卡目录,仅支持Android;
  /// 找到正确的本地路径
  /// getApplicationDocumentsDirectory 类似iOS的NSDocumentDirectory和Android上的AppData目录
  get localDocPath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }

  /// getTemporaryDirectory 类似iOS的NSTemporaryDirectory和Android的getCacheDir
  get localTempPath async {
    final directory = await getTemporaryDirectory();
    return directory.path;
  }

  ///创建文件夹
 setFileFolder(String path) async{
    Directory directory = new Directory('$path');
    if (!directory.existsSync()) {
      directory.createSync();
      debugPrint('文件夹初始化成功,文件保存路径为 ${directory.path}');
    } else {
      debugPrint('文件夹已存在');
    }
    return directory.path;
  }

  ///创建文件
  setFile(String path) {
    File file = new File('$path');
    if (!file.existsSync()) {
      file.createSync();
      debugPrint('创建成功');
    } else {
      debugPrint('文件已存在');
    }
    return file;
  }

  /// 将数据写入文件
  void writeCounter(String path, String content) async{
    // Write the file
    File file = await setFile(path);
    try {
      file.writeAsStringSync('$content');
      debugPrint('文件写入成功');
    } catch (e) {
      debugPrint('文件写入失败');
    }
  }

  /// 从文件中读取数据
  readCounter(String path) async {
    File file = await setFile(path);
    try {
      // Read the file
      String contents = file.readAsStringSync();
      debugPrint('文件读取成功:$contents');
      return contents;
    } catch (e) {
      debugPrint('文件读取失败');
      return '';
    }
  }

  ///文件/文件夹删除
  deleteFilefloder(String path) {
    Directory directory = new Directory(path);
    if (directory.existsSync()) {
      List<FileSystemEntity> files = directory.listSync();
      if (files.length > 0) {
        files.forEach((file) {
        file.deleteSync();
        });
      }
      directory.deleteSync();
      debugPrint('文件夹删除成功');
    }
  }

  ///删除文件
  deleteFile(String path) {
    File file = new File('$path');
    if (file.existsSync()) {
      try {
        file.deleteSync();
        debugPrint('文件删除成功');
      } catch (e){
        debugPrint('文件删除失败');
      }
    }
  }

  ///遍历所有文件
  getAllSubFile(String path) async{
    Directory directory = new Directory(path);
    if (directory.existsSync()) {
      return directory.listSync();
    }
    return [];
  }
}
上一篇下一篇

猜你喜欢

热点阅读