aspose file tools*
The moose likes I/O and Streams and the fly likes How to Copy All files with certain extensions from a directory and all its subs Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "How to Copy All files with certain extensions from a directory and all its subs" Watch "How to Copy All files with certain extensions from a directory and all its subs" New topic
Author

How to Copy All files with certain extensions from a directory and all its subs

Yasin Kothia
Ranch Hand

Joined: Sep 25, 2009
Posts: 39
I know how to copy a file from one directory to another, what i would like help on is copy a file with .jpg or .doc extension.

So for example.

Copy all files from D:/Pictures/Holidays

Scanning all folders in the above path and transfer all jpg's to a destination provided.

Any help would be appreciated.



Thanks
Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2848
    
  11

Check out java.io.FilenameFilter Both java.io.File.list() and java.io.File.listFiles() are overloaded to take a FilenameFilter to filter file listings. You should also be careful to handle name collisions. That is, if you have picture.jpg and something with that name already exists in the destination directory, what do you want to do? Overwrite it? Skip it? Rename one or both of them? You'll want to test that carefully before letting it loose on your real image files.
Nomaan Butt
Ranch Hand

Joined: Oct 19, 2011
Posts: 54
hope the below code will be usefull,

class AcceptFile implements FilenameFilter{

String pattern;

AcceptFile(String pattern){
this.pattern=pattern;
}

public boolean accept(File file,String name ){
if(){
name.endsWith(pattern);
return true;
}
else return false;
}

}

class FetchFiles{

String path = "D:/Pictures/Holidays";
String[] files;
File search = File(path);

files = search.list(AcceptFile(".jpg"));

}


This will fetch all the files with extension .jpg from D:/Pictures/Holidays. Here i have user FilenameFilter interface and have implemeted its accept method so that it accepts only those file of provided extension.
Yasin Kothia
Ranch Hand

Joined: Sep 25, 2009
Posts: 39
Thanks for the response guys, it really helped.
Harsha Smith
Ranch Hand

Joined: Jul 18, 2011
Posts: 287
Even simpler
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to Copy All files with certain extensions from a directory and all its subs