Compactar Diretorio

0 respostas
V

Ola pessoal, fiz um metodo que move os arquivos .txt para dentro do diretorio criado com a data atual, e chamo outro metodo para compactar este diretorio, so que tem um problema ele cria um arquivo .zip do diretorio atual e compacta a pasta com o zip dentro como faco para compactar apenas o diretorio sem jogar o .zip dentro…
aqui esta o codigo se alguem puder me ajudar. … ficarei grata…

package compactar;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.text.DateFormat;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Calendar;

import java.util.Collections;

import java.util.Date;

import java.util.GregorianCalendar;

import java.util.List;

import java.util.zip.Adler32;

import java.util.zip.CheckedOutputStream;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

public class Final {

public static String dir ="C:\\log";
public static String newPath = "";
public static String dirAtual = "";

public static boolean deleteDir(File newPath) 
{
    File candir;
    try 
    {
        candir = newPath.getCanonicalFile();
        System.out.println("candir "+candir);
    } 
    catch (IOException e) 
    {
        return false;
    }
    if (!candir.equals(newPath.getAbsoluteFile())) 
    {
        return false;
    }
    File[] files = candir.listFiles();
    if (files != null) 
    {
        for (int i = 0; i < files.length; i++) 
        {
            File file = files[i];
            boolean deleted = file.delete();
            if (!deleted) 
            {
                if (file.isDirectory()) deleteDir(file);
            }
        }
    }
    return newPath.delete();  
}

/**
 * Lê um arquivo passado no parâmetro para a memória.
 * @param file Arquivo a ser lido.
 * @return Arquivo lido em bytes.
 * @throws Exception
 */
private static byte[] read(File file) throws Exception 
{
    byte[] result = null;
    if (file != null && !file.isDirectory()) 
    {
        final long length = file.length();
        result = new byte[(int) length];
        InputStream fi = new FileInputStream(file);// FileInputStream - controla o fluxo de byte entrando
        byte b;
        long count = 0;
        while ((b = (byte) fi.read()) != -1) 
        {
            result[(int) count++] = b;
        }
        fi.close();
    }
    return result;
}

/**
 * Adiciona um diretório ou arquivo a um ZipOutputStream instanciado.
 * @param zipName - Nome no arquivo zip que será gerado, exeplo: C:\\log.zip
 * @param file - Nome do diretório a ser comprimido.
 * @throws Exception
 */
private static void addToZip(ZipOutputStream out, File file, String path) throws Exception 
{
    byte data[] = null;
    ZipEntry entry = null;
    if (file != null) 
    {
        String newPath = file.getAbsolutePath().replace('\\', '/');
        System.out.println(">>>> Adding newPath: " +newPath);
        
        if (file != null) 
        {System.out.println("teste "+file.getName());
        	if(file.getName().indexOf(".zip")>0)
        	{ System.out.println("teste if"+file.getName());           		            
                if (file.isDirectory()) 
                {
                    File[] files = file.listFiles();
                    for (File f : files) 
                    {
                        addToZip(out, f, path);
                        System.out.println("out"+out);
                        System.out.println("f"+f);
                        System.out.println("path"+path);
                    }
                }
        	}
            else 
            {
                entry = new ZipEntry(newPath);                   
                out.putNextEntry(entry);
                System.out.println("out (entry)"+out);
                data = read(file);
                if (data != null && data.length > 0) 
                {
                    out.write(data, 0, data.length);
                }
                out.closeEntry();
                out.flush();
            }
        }
    }
}


/**
 * Comprime um diretório ou arquivo.
 * @param zipName - Nome no arquivo zip que será gerado, exemplo: C:\\myzip.zip
 * @param dirName - Nome do arquivo ou diretório a ser comprimido.
 * Instancia um ZipOutputStream e o passa por parametro, isso para poder
 * finalizar com um out.close(). */
public static void zip(String dirName, String zipName) 
{
    ZipOutputStream out = null;
    FileOutputStream dest = null;
    CheckedOutputStream checksum = null;

    try 
    {
        dest = new FileOutputStream(new File(zipName));
        checksum = new CheckedOutputStream(dest, new Adler32());
        out = new ZipOutputStream(new BufferedOutputStream(checksum));
        File di = new File(dirName);
        if(di.isDirectory()) 
        {
            addToZip(out, di, di.getAbsolutePath());
            System.out.println("zip out"+out);
            System.out.println("zip di"+di);
            System.out.println("zip di.getAbsol.." + di.getAbsolutePath());
        }
        else 
        {
            String parent = di.getParent();
            System.out.println("parent "+parent);
            int length = parent.length();
            String substring = parent.substring(0, length);                
            addToZip(out, di, substring);
        }
        System.out.println(">>>> checksum: " + checksum.getChecksum().getValue());
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    } 
    catch (Error err) 
    {
        err.printStackTrace();
    }
    finally 
    {
        try 
        {
            out.flush();
            out.finish();
            out.close();
        }
        catch (IOException e) 
        {
            e.printStackTrace();
        }
        catch (Error err) 
        {
            err.printStackTrace();
        }
    }
}
public static void criarDiretorio(String path)

{

List<File> files = new ArrayList<File>();

Collections.addAll(files, new File(path).listFiles());
for(File element : (List&lt;File&gt;) files) 
      { 
         if(element.isDirectory()) 
         { 
             SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy"); 
             newPath = element.getAbsolutePath() + "\\" + element.getName() + "_" + simpleDateFormat.format(new Date()) ; 
             if(new File(newPath).mkdirs()) 
                System.out.println("Diretorio criado com sucesso");    	             
             moveFile(path + "\\" + element.getName(), newPath); 
   	         String atual = dirAtual + newPath;
   	         System.out.println("atual "+atual);
   	         System.out.println("element.getAbs.. "+element.getAbsolutePath());
             zip(element.getAbsolutePath(),atual+".zip"); 	             	           
         }    	      
      } 
   } 
    
   public static void moveFile(String path, String newPath) 
   { 
    	Date ultimaModificacao;   
        DateFormat dateFormatter;  
       
        Date hoje = new Date(java.lang.System.currentTimeMillis());        //java.util.Date hoje = new java.util.Date(java.lang.System.currentTimeMillis());
        Calendar calendar = new GregorianCalendar();//Cria uma instancia da classe Calendar(),  GregorianCalendar() essa classe permite fazer operacoes com a data ex - somar ou diminuir
        calendar.setTime(hoje);        //volta a ter um objeto como Date              
        calendar.add(Calendar.DAY_OF_MONTH, -3);  
        Date trintaAMenos = new Date(calendar.getTimeInMillis());                
	   
   	      List&lt;File&gt; files = new ArrayList&lt;File&gt;(); 
   	      Collections.addAll(files, new File(path).listFiles()); 
   	        
   	      for(File element : (List&lt;File&gt;) files) 
   	      { 
   	         if(element.getName().indexOf(".txt") &gt; 0) 
   	         { 
   	        	 System.out.println("element.getName "+element.getName());
            	 dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT); 
            	 ultimaModificacao = new Date(element.lastModified());                   
                 if (trintaAMenos.compareTo(ultimaModificacao)==-1) //= 1 a ultimaModeficacao e maior do que trintaAMenos
                 {
                	 element.renameTo(new File(newPath + "\\" + element.getName()));                    	 
                 }
   	         } 
   	      } 
   } 
     


public static void main(String[] args) 
{                  
	criarDiretorio(dir);
    deleteDir(new File (newPath));	
}

}

Criado 7 de junho de 2007
Respostas 0
Participantes 1