import 'dart:convert'; import 'dart:io'; import 'package:path/path.dart' as path; /// 文件操作工具类 class FileHelper { /// 私有构造函数,防止实例化 FileHelper._(); /// 读取 JSON 文件并解析 static Map readJsonFile(String filePath) { final file = File(filePath); if (!file.existsSync()) { throw FileNotFoundException('文件不存在: $filePath'); } try { final content = file.readAsStringSync(); return json.decode(content) as Map; } on FormatException catch (e) { throw FileParseException('JSON 解析错误: ${e.message}'); } } /// 写入文件内容 /// /// 如果目录不存在,会自动创建 static void writeFile(String filePath, String content) { final file = File(filePath); final directory = file.parent; // 确保目录存在 if (!directory.existsSync()) { directory.createSync(recursive: true); } file.writeAsStringSync(content); } /// 检查文件是否存在 static bool fileExists(String filePath) { return File(filePath).existsSync(); } /// 获取相对于工作目录的绝对路径 static String resolvePropertyPath(String relativePath, {String? workingDir}) { final directory = workingDir ?? Directory.current.path; if (path.isAbsolute(relativePath)) { return relativePath; } return path.join(directory, relativePath); } /// 获取文件的目录路径 static String getDirectoryPath(String filePath) { return path.dirname(filePath); } /// 获取文件名(不含扩展名) static String getFileNameWithoutExtension(String filePath) { return path.basenameWithoutExtension(filePath); } /// 获取文件名(含扩展名) static String getFileName(String filePath) { return path.basename(filePath); } } /// 文件未找到异常 class FileNotFoundException implements Exception { FileNotFoundException(this.message); final String message; @override String toString() => 'FileNotFoundException: $message'; } /// 文件解析异常 class FileParseException implements Exception { FileParseException(this.message); final String message; @override String toString() => 'FileParseException: $message'; }