You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Dart实现检测子目录含.txt文件时复制其父目录

Dart 实现目录批量复制逻辑

功能说明

遍历指定搜索目录下的所有子目录,若某个子目录中存在 .txt 文件,则将该子目录的父目录完整复制到指定目标目录中。

实现代码

import 'dart:io';
import 'package:path/path.dart' as path;

// 核心函数:检查子目录并复制符合条件的父目录
void copyParentDirIfHasTxt(String searchDirPath, String targetDirPath) async {
  // 验证搜索目录是否存在
  final searchDir = Directory(searchDirPath);
  if (!await searchDir.exists()) {
    print('错误:搜索目录不存在 -> $searchDirPath');
    return;
  }

  // 创建目标目录(若不存在)
  final targetDir = Directory(targetDirPath);
  if (!await targetDir.exists()) {
    await targetDir.create(recursive: true);
    print('已创建目标目录 -> $targetDirPath');
  }

  // 遍历搜索目录下的所有子目录
  await for (final entity in searchDir.list(recursive: false, followLinks: false)) {
    if (entity is Directory) {
      final subDir = entity;
      bool hasTxtFile = false;

      // 检查当前子目录是否存在.txt文件
      await for (final fileEntity in subDir.list(recursive: false, followLinks: false)) {
        if (fileEntity is File && path.extension(fileEntity.path) == '.txt') {
          hasTxtFile = true;
          break; // 找到一个就停止检查,提升效率
        }
      }

      if (hasTxtFile) {
        // 获取当前子目录的父目录
        final parentDir = Directory(path.dirname(subDir.path));
        // 拼接目标路径:目标目录 + 父目录名称
        final targetParentPath = path.join(targetDirPath, path.basename(parentDir.path));

        // 递归复制父目录到目标路径
        await _copyDirectory(parentDir, Directory(targetParentPath));
        print('已复制目录 -> ${parentDir.path} 到 -> $targetParentPath');
      }
    }
  }
}

// 递归复制目录(包含所有子文件和子目录)
Future<void> _copyDirectory(Directory source, Directory target) async {
  await target.create(recursive: true);
  
  await for (final entity in source.list(recursive: false)) {
    final targetEntity = path.join(target.path, path.basename(entity.path));
    
    if (entity is File) {
      await entity.copy(targetEntity);
    } else if (entity is Directory) {
      await _copyDirectory(entity, Directory(targetEntity));
    }
  }
}

// 示例调用
void main() async {
  const searchDirectory = '/path/to/your/search/dir';
  const targetDirectory = '/path/to/your/target/dir';
  
  await copyParentDirIfHasTxt(searchDirectory, targetDirectory);
  print('任务完成');
}

关键说明

  • 使用 dart:io 处理文件系统操作,path 库处理路径拼接与解析
  • 遍历目录时通过 recursive: false 确保只处理当前层级的子目录
  • 找到 .txt 文件后立即终止当前子目录的文件检查,减少不必要的遍历
  • _copyDirectory 函数实现递归复制,确保目录下的所有内容都被完整迁移
  • 新增基础错误提示,避免因输入无效路径导致无反馈的问题

内容的提问来源于stack exchange,提问作者George Walker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 16:37:47