sexta-feira, 30 de julho de 2010

[javautils] deleteFile

   /**
    * Exclui um arquivo (e seus subdiretorios e sub arquivos, se ele for um diretorio)
    *
    * @param filename
    * @param silent - se true, não gera nenhuma exceção mesmo que não consiga excluir o arquivo
    */
   public static void deleteFile(String filename, boolean silent) {

      File arquivo = new File(filename);

      /*
       * Se o arquivo não for um diretório, é deletado. Caso seja um diretório, é deletado com
       * seus subdiretórios e arquivos.
       */
      if (!arquivo.isDirectory()) {
         JavaUtils.subDeleteFile(filename, silent, arquivo);
      } else {
         File[] listFiles = arquivo.listFiles();

         for (int i = 0; i < listFiles.length; i++) {
            File arquivoFilho = listFiles[i];
            JavaUtils.deleteFile(arquivoFilho.getAbsolutePath(), silent);
         }
         JavaUtils.subDeleteFile(filename, silent, arquivo);
    }
   }  
  

   /**
    * Usado pelo deleteFile. Tenta apagar o arquivo e faz o tratamento de exceção.
    *
    * @param filename
    * @param silent
    * @param arquivo
    */
   protected static void subDeleteFile(String filename, boolean silent, File arquivo) {
      boolean excluiu = false;
      try {
         excluiu = arquivo.delete();
      } catch (Throwable e) {

         if (!silent) {
            // Se silent for false, gera exceção.
            throw new RuntimeException(
                     "JavaUtils.deleteFile() - Erro desconhecido ao excluir o arquivo \"" +
                              filename + "\". Error: " + e);
         }
      }

      if (!excluiu && !silent) {
         //Se não conseguir excluir o arquivo, gera exceção.
         throw new RuntimeException(
                  "JavaUtils.deleteFile() - Erro desconhecido. Não conseguiu excluir o arquivo com o nome \"" +
                           filename +
                           "\". Pode ser que o arquivo não exista, por isso o erro.");
      }
   }  

Nenhum comentário: