本次主要實(shí)現(xiàn)文件/文件夾的創(chuàng)建拦耐、刪除空民、寫入狡耻、讀取具體代碼如下:
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;
}
///創(chuàng)建文件夾
setFileFolder(String path) async{
Directory directory = new Directory('$path');
if (!directory.existsSync()) {
directory.createSync();
debugPrint('文件夾初始化成功悉抵,文件保存路徑為 ${directory.path}');
} else {
debugPrint('文件夾已存在');
}
return directory.path;
}
///創(chuàng)建文件
setFile(String path) {
File file = new File('$path');
if (!file.existsSync()) {
file.createSync();
debugPrint('創(chuàng)建成功');
} else {
debugPrint('文件已存在');
}
return file;
}
/// 將數(shù)據(jù)寫入文件
void writeCounter(String path, String content) async{
// Write the file
File file = await setFile(path);
try {
file.writeAsStringSync('$content');
debugPrint('文件寫入成功');
} catch (e) {
debugPrint('文件寫入失敗');
}
}
/// 從文件中讀取數(shù)據(jù)
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 [];
}
}