Java: how to copy a directory but exclude some directories deep inside main directory

陌路散爱 提交于 2019-12-10 11:38:49

问题


Using java, I want to copy whole directory excluding some sub-directories (and all files inside those sub-directories) down file path. How can I do that? I've seen several such questions on SO but using Perl/ANT etc but not using Java.


回答1:


Try FileUtils.html#copyDirectory from Apache Commons IO. One of the overloaded versions take FileFilter instance with single straightforward method to be implemented by you:

boolean accept(File pathname)

Also look at the list of existing convenient FileFilter implementations in Commons IO:

  • AgeFileFilter
  • AndFileFilter
  • CanReadFileFilter
  • CanWriteFileFilter
  • DelegateFileFilter
  • DirectoryFileFilter
  • EmptyFileFilter
  • FileFileFilter
  • HiddenFileFilter
  • MagicNumberFileFilter
  • NameFileFilter
  • NotFileFilter
  • OrFileFilter
  • PrefixFileFilter
  • RegexFileFilter
  • SizeFileFilter
  • SuffixFileFilter
  • WildcardFileFilter
  • WildcardFilter



回答2:


You can do it the same way you would in any other language

  1. Start at the root of the source directory
  2. Go through all children (using Breadth-First-Search for example)
  3. If you want to ignore the child, ignore it If the child is a directory, use File.mkdir() on that child If the child is a file, copy it Open the file using a FileInputStream Writing the data you read to a new file using a FileOutputStream
  4. Repeat with each child directory

Or, you can do this the easy way
1. Apache FileUtils
2. Java File Copy Library project



来源:https://stackoverflow.com/questions/6205167/java-how-to-copy-a-directory-but-exclude-some-directories-deep-inside-main-dire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!