Reputation: 15
The code I have works for copying all direcotries and files but not sure on how to exclude a
particular directory under music and exclude a list of files
1) For example, I have Music folder and lots of subdirectories. Want to exclude spanish subdirectory and copy everything under Music folder to destination
The second condition which I wanted to check is
2) Under Music folder I wanted to exclude all text files and copy
` private void copyFiles(File src, File tgt) throws IOException
{
if(src.isDirectory())
{
try{
if(!tgt.exists()) tgt.mkdirs();
String[] filePaths = src.list();
for(String filePath : filePaths)
{
File srcFile = new File(src, filePath);
File destFile = new File(tgt, filePath);
copyFiles(srcFile, destFile);
}
}
catch(Exception ie)
{
ie.printStackTrace();
}
}
else
{
try
{
bis = new BufferedInputStream(new FileInputStream(src));
bos = new BufferedOutputStream(new FileOutputStream(tgt));
long fileBytes = src.length();
long soFar = 0;
int Byte;
while((Byte = bis.read()) != -1)
{
bos.write(Byte);
}
bis.close();
bos.close();
}
catch(Exception excep)
{
excep.printStackTrace();
bos.flush();
bis.close();
bos.close();
}`
Upvotes: 1
Views: 4968
Reputation: 347314
File#listFiles
takes a FileFilter
which can be used to determine if certain files should be included or not in the listing returne by File#listFiles
...
This is okay if you know in advance what you to to include/exclude. If you want to make the process more dynamic, you could pass a list of FileFilter
s to the copy
method and then use a special FileFilter
to iterate over them...
private void copyFiles(File src, File tgt, FileFilter... filters) {
/*...*/
File[] filePaths = src.listFiles(new GroupedFileFiler(filters));
/*...*/
}
public class GroupedFileFilter implements FileFilter {
private FileFilter[] filters;
public GroupedFileFilter(FileFilter... filters) {
this.filters = filters;
}
@Override
public boolean accept(File pathname) {
boolean include = true;
if (filters != null && filters.length > 0) {
for (FileFilter filter : filters) {
include = filter.accept(pathname);
if (!include) {
break;
}
}
}
return include;
}
}
Upvotes: 2