Reunir varios arquivos em um so

4 respostas
R

Estou tentando fazer um “compactador” em java, mas estou tendo problemas quando vou descarregar os arquivos.

O problema e o seguinte: Quero reunir em um unico arquivo, um diretorio com seus arquivos e subdiretorios. Na parte de reunir esta tudo certo mas na hora de fazer o sentido inverso estou tento problema pois os arquivos estao vindo sem conteudo…
Obirgado.

4 Respostas

R
/*
 * Created on 01/06/2004
 *
 * To change the template for this generated file go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
package framework.testeFPF.agrupador;

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.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Vector;

import framework.testeFPF.arquivo.Arquivo;
import framework.testeFPF.excecoes.NomeArquivoInvalidoException;

/**
 * @author Romulo Quidute
 *
 * To change the template for this generated type comment go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
public class Agrupador implements Serializable {
	public Agrupador(File diretorio) {
		this.diretorio = diretorio;
	}

	public void agrupar() throws IOException, ClassNotFoundException {
		oSaida =
			new ObjectOutputStream(
				new FileOutputStream(diretorio.getPath() + ".prv"));

		dados = diretorio.listFiles();

		Arquivo a = new Arquivo(diretorio.getPath());
		System.err.println(
			"Compactando o Diretorio Principal(" + a.getPath() + ")");

		//Escrever o Diretorio Principal no arquivo de Saida
		oSaida.writeObject(a);

		agruparConteudo(dados);

		oSaida.flush();
		oSaida.close();

	}

	public void desagrupar()
		throws IOException, ClassNotFoundException, NomeArquivoInvalidoException {
		String nome = diretorio.getName();

		if (!nome.substring(nome.length() - 4, nome.length()).equals(".prv"))
			throw new NomeArquivoInvalidoException();

		ObjectInputStream ois =
			new ObjectInputStream(new FileInputStream(diretorio.getPath()));

		Arquivo a = (Arquivo) ois.readObject();
		a.mkdir();
		System.err.println(
			"Descompactando o Diretório Principal(" + a.getPath() + ")");

		Vector arquivos = new Vector();

		try {
			while (true) {
				arquivos.addElement((Arquivo) ois.readObject());
			}
		} catch (IOException e) {

		}

		for (int i = arquivos.size() - 1; i >= 0; i--) {
			a = (Arquivo) arquivos.get(i);

			a.setPath(a.getCaminho() + "\" + a.getName());

			if (a.getEDiretorio()) {
				a.mkdir();
				System.err.println(
					"Descompactando o Diretório(" + a.getPath() + ")");
			} else {
				System.out.println(
					"Descompactando o Arquivo(" + a.getPath() + ")");

				//Criar arquivos temporário,
				//para serem copiados no diretorio de destino
				ObjectOutputStream aux =
					new ObjectOutputStream(new FileOutputStream(a.getPath()));
				aux.flush();
				aux.close();
				//

				FileInputStream fis = new FileInputStream(a);

				copyInputStream(
					fis,
					new BufferedOutputStream(
						new FileOutputStream(a.getPath())));
			}

		}
	}

	//Metodo para agrupar o conteudo do diretório
	//Chamada recursida para os subdiretorios
	public void agruparConteudo(File[] arquivo)
		throws IOException, ClassNotFoundException {
		for (int i = 0; i < arquivo.length; i++) {

			if (arquivo[i].isDirectory()) {
				File t = new File(arquivo[i].getAbsolutePath());
				agruparConteudo(t.listFiles());
			}

			Arquivo a = new Arquivo(arquivo[i], "");

			a.setCaminho(arquivo[i].getAbsolutePath());
			a.setPath(a.getCaminho() + "\" + a.getName());

			//"Setar" que o arquivo e um Diretorio
			a.setEDiretorio(a.isDirectory());

			if (a.getEDiretorio())
				System.err.println(
					"Compactando o Diretorio(" + a.getPath() + ")");
			else
				System.out.println(
					"Compactando o Arquivo(" + a.getPath() + ")");

			//Adicionar o Arquivo/Diretorio ao Arquivo Agrupado
			oSaida.writeObject(a);

		}
	}

	//Metodo para copiar A entrada do arquivo agrupado de origem, 
	//em um arquivo de saida
	public static final void copyInputStream(InputStream in, OutputStream out)
		throws IOException {
		byte[] buffer = new byte[1024];
		int len;
		while ((len = in.read(buffer)) >= 0)
			out.write(buffer, 0, len);
		in.close();
		out.close();
	}

	private static ObjectOutputStream oSaida;
	private File[] dados;
	private File diretorio;
}
/*
 * Created on 01/06/2004
 *
 * To change the template for this generated file go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
package framework.testeFPF.arquivo;

import java.io.File;

/**
 * @author Romulo Quidute
 *
 * To change the template for this generated type comment go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
public class Arquivo extends File {

	public Arquivo(String arquivo) {
		super(arquivo);
		path = arquivo;
	}

	public Arquivo(File arquivo, String nome) {
		super(arquivo, nome);
	}

	public String getCaminho() {
		return caminho;
	}

	//"Setar" o caminho do arquivo sem o Nome, apenas com o diretorio
	public void setCaminho(String caminho) {
		int pos = caminho.indexOf(getName());
		this.caminho = caminho.substring(0, pos - 1);
	}

	//Metodo para "Setar" o path
	public void setPath(String path) {
		this.path = path;
	}

	//	Metodo sobreEscrito getPath
	public String getPath() {
		return path;
	}

	public boolean getEDiretorio() {
		return eDiretorio;
	}

	public void setEDiretorio(boolean eDiretorio) {
		this.eDiretorio = eDiretorio;
	}

	private boolean eDiretorio;
	//Atributo sobreEscrito path
	private String path = "";
	private String caminho;
	private byte[] valor;
}
R
/*
 * Created on 01/06/2004
 *
 * Sistema que reune um Um diretorio com seus arquivos e subdiretorio 
 * em apenas um único arquivo
 */
package framework.testeFPF.gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import framework.testeFPF.agrupador.Agrupador;
import framework.testeFPF.excecoes.NomeArquivoInvalidoException;

/**
 * @author Romulo Quidute
 *
 */
public class FrmPrincipal extends JFrame {
	public FrmPrincipal() {
		iniciarTela();

		setSize(330, 180);

		//Centralizar o Form
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		Dimension frameSize = getSize();
		setLocation(
			(screenSize.width - frameSize.width) / 2,
			((screenSize.height - frameSize.height) / 2));
		//

		show();
	}

	private void iniciarTela() {
		pnPrincipal = new JPanel();
		btExtract = new JButton();
		btGroup = new JButton();

		setTitle("Teste Compactador");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

		btGroup.setText("Group");
		btGroup.setMnemonic('G');
		btGroup.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				btGroupActionPerformed();
			}

		});

		btExtract.setText("Extract");
		btExtract.setMnemonic('E');
		btExtract.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				btExtractActionPerformed();
			}

		});

		btExtract.setBounds(50, 45, 100, 25);
		btGroup.setBounds(170, 45, 100, 25);

		pnPrincipal.setLayout(null);

		pnPrincipal.add(btExtract);
		pnPrincipal.add(btGroup);

		getContentPane().add(pnPrincipal, BorderLayout.CENTER);

		pack();
	}

	private void btGroupActionPerformed() {
		try {
			File diretorio = selecionarDiretorio(true);

			if (diretorio == null)
				return;

			Agrupador c = new Agrupador(diretorio);
			c.agrupar();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	//Método que irá abrir a Caixa para escolher o diretorio a ser agrupado
	//È chamado tanto para agrupar(Diretorio) quanto para desagrupar(Arquivo)
	private File selecionarDiretorio(boolean arquivo) {
		JFileChooser fcDiretorio = new JFileChooser();

		if (arquivo)
			fcDiretorio.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		else
			fcDiretorio.setFileSelectionMode(JFileChooser.FILES_ONLY);

		File diretorio = null;

		int resposta = fcDiretorio.showDialog(this, "Selecione");
		if (resposta != JFileChooser.CANCEL_OPTION) {
			diretorio = fcDiretorio.getSelectedFile();
		} else {
			return null;
		}

		return diretorio;
	}

	private void btExtractActionPerformed() {
		try {
			File diretorio = selecionarDiretorio(false);

			if (diretorio == null)
				return;

			Agrupador c = new Agrupador(diretorio);
			c.desagrupar();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (NomeArquivoInvalidoException e) {
			JOptionPane.showMessageDialog(this, e.getMessage());
			e.printStackTrace();
		}
	}

	public static void main(String args[]) {
		new FrmPrincipal();
	}

	private JPanel pnPrincipal;
	private JButton btGroup;
	private JButton btExtract;
}
R

Copiar Um atributo vector contendo bytes

/*
 * Created on 01/06/2004
 *
 * To change the template for this generated file go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
package framework.Teste.agrupador;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Vector;

import framework.Teste.arquivo.Arquivo;
import framework.Teste.excecoes.NomeArquivoInvalidoException;

/**
 * @author Romulo Quidute
 *
 * To change the template for this generated type comment go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
public class Agrupador implements Serializable {
	public Agrupador(File diretorio) {
		this.diretorio = diretorio;
	}

	public void agrupar() throws IOException, ClassNotFoundException {
		oSaida =
			new ObjectOutputStream(
				new FileOutputStream(diretorio.getPath() + ".prv"));

		dados = diretorio.listFiles();

		Arquivo a = new Arquivo(diretorio.getPath());
		System.err.println(
			"
Compactando o Diretorio Principal(" + a.getPath() + ")");

		//Escrever o Diretorio Principal no arquivo de Saida
		oSaida.writeObject(a);

		agruparConteudo(dados);

		oSaida.flush();
		oSaida.close();

	}

	public void desagrupar()
		throws IOException, ClassNotFoundException, NomeArquivoInvalidoException {
		String nome = diretorio.getName();

		if (!nome.substring(nome.length() - 4, nome.length()).equals(".prv"))
			throw new NomeArquivoInvalidoException();

		ObjectInputStream ois =
			new ObjectInputStream(new FileInputStream(diretorio.getPath()));

		Arquivo a = (Arquivo) ois.readObject();
		a.mkdir();
		System.err.println(
			"
Descompactando o Diretório Principal(" + a.getPath() + ")");

		Vector arquivos = new Vector();

		try {
			while (true) {
				arquivos.addElement((Arquivo) ois.readObject());
			}
		} catch (IOException e) {

		}

		for (int i = arquivos.size() - 1; i >= 0; i--) {
			a = (Arquivo) arquivos.get(i);

			a.setPath(a.getCaminho() + "\" + a.getName());

			if (a.getEDiretorio()) {
				a.mkdir();
				System.err.println(
					"Descompactando o Diretório(" + a.getPath() + ")");
			} else {
				System.out.println(
					"Descompactando o Arquivo(" + a.getPath() + ")");

				//Criar arquivos temporário,
				//para serem copiados no diretorio de destino
				ObjectOutputStream aux =
					new ObjectOutputStream(new FileOutputStream(a.getPath()));

				//Copiar conteudo(bytes) do arquivo que esta agrupado para o arquivo fisico 
				Vector conteudo = a.getConteudo();
				byte[] buffer = new byte[Arquivo.TAMANHO_BLOCO];
				if (conteudo != null) {
					Iterator it = conteudo.iterator();
					while (it.hasNext()) {
						buffer = (byte[]) it.next();
					}
					aux.write(buffer);
				}

				aux.flush();
				aux.close();
			}
		}
	}

	//Metodo para agrupar o conteudo do diretório
	//Chamada recursida para os subdiretorios
	public void agruparConteudo(File[] arquivo)
		throws IOException, ClassNotFoundException {
		for (int i = 0; i < arquivo.length; i++) {

			if (arquivo[i].isDirectory()) {
				File t = new File(arquivo[i].getAbsolutePath());
				agruparConteudo(t.listFiles());
			}

			Arquivo a = new Arquivo(arquivo[i], "");

			a.setCaminho(arquivo[i].getAbsolutePath());
			a.setPath(a.getCaminho() + "\" + a.getName());

			//"Setar" que o arquivo e um Diretorio
			a.setEDiretorio(a.isDirectory());

			if (a.getEDiretorio()) {

				System.err.println(
					"Compactando o Diretorio(" + a.getPath() + ")");
				a.setConteudo(null);
			} else {

				System.out.println(
					"Compactando o Arquivo(" + a.getPath() + ")");

				InputStream is = new FileInputStream(a.getPath());

				Vector conteudoAux = new Vector();
				byte[] buffer = new byte[1024];
				int len;
				int k = 0;
				while ((len = is.read(buffer)) >= 0) {
					byte[] bufferTemp = new byte[1024];
					for (int l = 0; l < buffer.length; l++)
						bufferTemp[l] = buffer[l];
					conteudoAux.addElement(bufferTemp);
				}
				a.setConteudo(conteudoAux);
			}

			//Adicionar o Arquivo/Diretorio ao Arquivo Agrupado
			oSaida.writeObject(a);

		}
	}

	//Metodo para copiar A entrada do arquivo agrupado de origem, 
	//em um arquivo de saida
	public static final void copyInputStream(InputStream in, OutputStream out)
		throws IOException {
		byte[] buffer = new byte[1024];
		int len;
		while ((len = in.read(buffer)) >= 0)
			out.write(buffer, 0, len);
		in.close();
		out.close();
	}

	private static ObjectOutputStream oSaida;
	private File[] dados;
	private File diretorio;
}
cv1

“Rominhof”:
Estou tentando fazer um “compactador” em java (…)

O problema e o seguinte: Quero reunir em um unico arquivo, um diretorio com seus arquivos e subdiretorios.

Hmm… pq o tar, gzip, bzip2 e zip e tantos outros compactadores nao resolve? :smiley:

No proprio Java, alias, existem APIs para se trabalhar com gzip e zip (os arquivos JAR nao sao nada mais do que ZIPs, afinal ;))

Criado 1 de junho de 2004
Ultima resposta 3 de jun. de 2004
Respostas 4
Participantes 2