Randomizando nomes de arquivos

18 Julho 2009

A idéia surgiu devido o aparelho de som do carro do meu pai não ser lá um iPod Shuffle. Então pensei:

Já que ele não randomiza muito bem, que tal levar os nomes dos arquivos já randomizados?

Decidi fazer rapidinho em Java e deu nisso aí:

RandomFiles.java

    
/*
 *  RandomFiles.java
 *  Copyright (C) 2009  Vítor Avelino
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.File;
import java.util.Random;

public class RandomFiles {

    private static Random randomizer = new Random();

    /**
    * Randomize the files of a specific directory.
    *
    * @param directory  The directory that will have its file renamed
    * @param subdir <code>true</code> if subdirectories' files have to be renamed
    *           <code>false</code> if it's not necessary rename subdirectories' files
    */
    public static void randomize(String directory, boolean includeSubdirs) {
        File dir = new File(directory);
        if (!dir.isDirectory() || !dir.exists()) {
            System.err.println(directory + " não é um diretório ou não existe!");
            System.exit(-1);
        }
        System.out.println("Inicializando renomeamento randômico...");
        navigateInDirectories(dir, includeSubdirs);
        System.out.println("Finalizado!");
    }

    private static void navigateInDirectories(File dir, boolean includeSubdirs) {
        File renamed = null;
        int randomNumber = 0;
        for (File f : dir.listFiles()) {
            do {
                randomNumber = randomizer.nextInt();
            } while (randomNumber <= 0);
            if (!f.isDirectory()) {
                renamed = new File(FileUtil.getPath(f) + randomNumber + FileUtil.getExtension(f));
                f.renameTo(renamed);
                System.out.println(">>> " + f.getName() + " renomeado para " + randomNumber + FileUtil.getExtension(f));
            } else if (includeSubdirs) {
                System.out.println("- " + f.getName() + File.separator);
                navigateInDirectories(f, includeSubdirs);
            }
        }
    }
}
    

FileUtil.java

    
/*
 *  FileUtil.java
 *  Copyright (C) 2009  Vítor Avelino
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.File;

public class FileUtil {

    /**
    * Returns just the pathname of a file as string.
    *
    * @param f The file that will have the path extracted
    * @return The pathname of a file
    */
    public static String getPath(File f) {
        String absolutePath = f.getAbsolutePath();
        return absolutePath.substring(0, absolutePath.lastIndexOf(File.separator) + 1);
    }

    /**
    * Returns the extension of a file.
    *
    * @param The file that will have the extension extracted
    * @return <code>null</code> if the extension of a file doesn't exist, <code>extension</code> if the file has one
    */
    public static String getExtension(File f) {
        String name = f.getName();
        return name.substring(name.lastIndexOf('.'));
    }

}
    

A forma de utilizar é simples, segue um exemplo abaixo:

    
RandomFiles.randomize("D:\Teste\", false);
RandomFiles.randomize("D:\Teste\", true);
    

Para a primeira chamada a saída será:

    
Inicializando renomeamento randômico...
>>> arquivo1.PDF renomeado para 538981388.PDF
>>> arquivo2.doc renomeado para 65861820.doc
>>> arquivo3.html renomeado para 210904720.html
Finalizado!
    

Para a segunda chamada a saída será:

    
Inicializando renomeamento randômico...
>>> 210904720.html renomeado para 668609286.html
>>> 538981388.PDF renomeado para 573146098.PDF
>>> 65861820.doc renomeado para 417987190.doc
- sub\
>>> arquivo4.PDF renomeado para 233716363.PDF
>>> arquivo5.doc renomeado para 657621617.doc
>>> arquivo6.html renomeado para 118165004.html
Finalizado!
    

As mensagens de saída foram utilizadas apenas para acompanhar a execução do programa.

Espero que seja útil para alguém assim como foi para mim. Quando tiver tempo farei uma versão em Python e/ou Shell-Script e também instalarei um SO decente (viram o exemplo lixo, né?) aqui no PC da casa dos meus pais.

Férias já! :~

blog comments powered by Disqus