问题
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
- Start at the root of the source directory
- Go through all children (using Breadth-First-Search for example)
- 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
- 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