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.
/* * Created on 01/06/2004 * * To change the template for this generated file go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */packageframework.testeFPF.agrupador;importjava.io.BufferedOutputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.ObjectInputStream;importjava.io.ObjectOutputStream;importjava.io.OutputStream;importjava.io.Serializable;importjava.util.Vector;importframework.testeFPF.arquivo.Arquivo;importframework.testeFPF.excecoes.NomeArquivoInvalidoException;/** * @author Romulo Quidute * * To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */publicclassAgrupadorimplementsSerializable{publicAgrupador(Filediretorio){this.diretorio=diretorio;}publicvoidagrupar()throwsIOException,ClassNotFoundException{oSaida=newObjectOutputStream(newFileOutputStream(diretorio.getPath()+".prv"));dados=diretorio.listFiles();Arquivoa=newArquivo(diretorio.getPath());System.err.println("Compactando o Diretorio Principal("+a.getPath()+")");//Escrever o Diretorio Principal no arquivo de SaidaoSaida.writeObject(a);agruparConteudo(dados);oSaida.flush();oSaida.close();}publicvoiddesagrupar()throwsIOException,ClassNotFoundException,NomeArquivoInvalidoException{Stringnome=diretorio.getName();if(!nome.substring(nome.length()-4,nome.length()).equals(".prv"))thrownewNomeArquivoInvalidoException();ObjectInputStreamois=newObjectInputStream(newFileInputStream(diretorio.getPath()));Arquivoa=(Arquivo)ois.readObject();a.mkdir();System.err.println("Descompactando o Diretório Principal("+a.getPath()+")");Vectorarquivos=newVector();try{while(true){arquivos.addElement((Arquivo)ois.readObject());}}catch(IOExceptione){}for(inti=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( "DescompactandooDiretório(" + a.getPath() + ")"); } else { System.out.println( "DescompactandooArquivo(" + 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( "CompactandooDiretorio(" + a.getPath() + ")"); else System.out.println( "CompactandooArquivo(" + 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&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */packageframework.testeFPF.arquivo;importjava.io.File;/** * @author Romulo Quidute * * To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */publicclassArquivoextendsFile{publicArquivo(Stringarquivo){super(arquivo);path=arquivo;}publicArquivo(Filearquivo,Stringnome){super(arquivo,nome);}publicStringgetCaminho(){returncaminho;}//"Setar" o caminho do arquivo sem o Nome, apenas com o diretoriopublicvoidsetCaminho(Stringcaminho){intpos=caminho.indexOf(getName());this.caminho=caminho.substring(0,pos-1);}//Metodo para "Setar" o pathpublicvoidsetPath(Stringpath){this.path=path;}// Metodo sobreEscrito getPathpublicStringgetPath(){returnpath;}publicbooleangetEDiretorio(){returneDiretorio;}publicvoidsetEDiretorio(booleaneDiretorio){this.eDiretorio=eDiretorio;}privatebooleaneDiretorio;//Atributo sobreEscrito pathprivateStringpath="";privateStringcaminho;privatebyte[]valor;}
R
Rominhof
/* * Created on 01/06/2004 * * Sistema que reune um Um diretorio com seus arquivos e subdiretorio * em apenas um único arquivo */packageframework.testeFPF.gui;importjava.awt.BorderLayout;importjava.awt.Dimension;importjava.awt.Toolkit;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.io.File;importjava.io.FileNotFoundException;importjava.io.IOException;importjavax.swing.JButton;importjavax.swing.JFileChooser;importjavax.swing.JFrame;importjavax.swing.JOptionPane;importjavax.swing.JPanel;importframework.testeFPF.agrupador.Agrupador;importframework.testeFPF.excecoes.NomeArquivoInvalidoException;/** * @author Romulo Quidute * */publicclassFrmPrincipalextendsJFrame{publicFrmPrincipal(){iniciarTela();setSize(330,180);//Centralizar o FormDimensionscreenSize=Toolkit.getDefaultToolkit().getScreenSize();DimensionframeSize=getSize();setLocation((screenSize.width-frameSize.width)/2,((screenSize.height-frameSize.height)/2));//show();}privatevoidiniciarTela(){pnPrincipal=newJPanel();btExtract=newJButton();btGroup=newJButton();setTitle("Teste Compactador");setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);btGroup.setText("Group");btGroup.setMnemonic('G');btGroup.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEventarg0){btGroupActionPerformed();}});btExtract.setText("Extract");btExtract.setMnemonic('E');btExtract.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEventarg0){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();}privatevoidbtGroupActionPerformed(){try{Filediretorio=selecionarDiretorio(true);if(diretorio==null)return;Agrupadorc=newAgrupador(diretorio);c.agrupar();}catch(FileNotFoundExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}catch(ClassNotFoundExceptione){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)privateFileselecionarDiretorio(booleanarquivo){JFileChooserfcDiretorio=newJFileChooser();if(arquivo)fcDiretorio.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);elsefcDiretorio.setFileSelectionMode(JFileChooser.FILES_ONLY);Filediretorio=null;intresposta=fcDiretorio.showDialog(this,"Selecione");if(resposta!=JFileChooser.CANCEL_OPTION){diretorio=fcDiretorio.getSelectedFile();}else{returnnull;}returndiretorio;}privatevoidbtExtractActionPerformed(){try{Filediretorio=selecionarDiretorio(false);if(diretorio==null)return;Agrupadorc=newAgrupador(diretorio);c.desagrupar();}catch(FileNotFoundExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}catch(ClassNotFoundExceptione){e.printStackTrace();}catch(NomeArquivoInvalidoExceptione){JOptionPane.showMessageDialog(this,e.getMessage());e.printStackTrace();}}publicstaticvoidmain(Stringargs[]){newFrmPrincipal();}privateJPanelpnPrincipal;privateJButtonbtGroup;privateJButtonbtExtract;}
R
Rominhof
Copiar Um atributo vector contendo bytes
/* * Created on 01/06/2004 * * To change the template for this generated file go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */packageframework.Teste.agrupador;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.ObjectInputStream;importjava.io.ObjectOutputStream;importjava.io.OutputStream;importjava.io.Serializable;importjava.util.Iterator;importjava.util.Vector;importframework.Teste.arquivo.Arquivo;importframework.Teste.excecoes.NomeArquivoInvalidoException;/** * @author Romulo Quidute * * To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */publicclassAgrupadorimplementsSerializable{publicAgrupador(Filediretorio){this.diretorio=diretorio;}publicvoidagrupar()throwsIOException,ClassNotFoundException{oSaida=newObjectOutputStream(newFileOutputStream(diretorio.getPath()+".prv"));dados=diretorio.listFiles();Arquivoa=newArquivo(diretorio.getPath());System.err.println("Compactando o Diretorio Principal("+a.getPath()+")");//Escrever o Diretorio Principal no arquivo de SaidaoSaida.writeObject(a);agruparConteudo(dados);oSaida.flush();oSaida.close();}publicvoiddesagrupar()throwsIOException,ClassNotFoundException,NomeArquivoInvalidoException{Stringnome=diretorio.getName();if(!nome.substring(nome.length()-4,nome.length()).equals(".prv"))thrownewNomeArquivoInvalidoException();ObjectInputStreamois=newObjectInputStream(newFileInputStream(diretorio.getPath()));Arquivoa=(Arquivo)ois.readObject();a.mkdir();System.err.println("Descompactando o Diretório Principal("+a.getPath()+")");Vectorarquivos=newVector();try{while(true){arquivos.addElement((Arquivo)ois.readObject());}}catch(IOExceptione){}for(inti=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( "DescompactandooDiretório(" + a.getPath() + ")"); } else { System.out.println( "DescompactandooArquivo(" + 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( "CompactandooDiretorio(" + a.getPath() + ")"); a.setConteudo(null); } else { System.out.println( "CompactandooArquivo(" + 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?
No proprio Java, alias, existem APIs para se trabalhar com gzip e zip (os arquivos JAR nao sao nada mais do que ZIPs, afinal ;))