• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Yasin Kothia
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2984
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 54
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the response guys, it really helped.
 
Harsha Smith
Ranch Hand
Posts: 287
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even simpler
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic