vrijdag 20 juli 2012

Howto create a set of folders on the fly

Intro
In this blog I would like to show what is the easiest way in java to create a set of folders.
I took for this example the folder structure of images and created the icon folders for them (lazy as I am :-) )

The problem
The structure of my images folders would be:

images/image_galery_1
images/image_galery_2
images/image_galery_3
images/image_galery_4.

In the past I would loop through the forrest of folder to find these four. There is a much easier way and copy them with other names:


The solution
        FilenameFilter imageFilter = new ImageFilter();
        File[] imagesFolders = new File("images",.listFiles(imageFilter);

java.io.FileNameFilter is a standard java interface that helps you to identify the folders you looking for. Create a class yourself that implements this Interface. The class would look something like this:

public class ImageFilter implements FilenameFilter {
    private static final String FOLDER_PRE_FIX="image";

    @Override
    public boolean accept(File dir, String name) {
        boolean fileImage=false;
        if(name.startsWith(FOLDER_PRE_FIX)){
            fileImage=true;
        }
        return fileImage;
    }

In this example I just used a simple 2 layered folder structure. You can imagine that in a more complex structure this way realy is helpfull.

After running this loop you automated the creation of the icon folders with minimized lines of code :
    private static final String ICONS = "icons";
    private static final String IMAGES = "images";

Looping through the results  the following way:
        for (File file : imagesFolders) {
           //Just to be sure nothing slips through.
            if(file.isDirectory()){
                String filePath = file.getAbsolutePath().replace(IMAGES, ICONS);
                File iconsFolder = new File(filePath);
                iconsFolder.mkdirs();
            }

have fun!

Geen opmerkingen:

Een reactie posten