How to download a compressed file from a URL and save to disk?

Asked

Viewed 1,025 times

1

I made a java program to download a compressed (zip) file from a server from a URL (in this case, I am using localhost to test), but it is giving the following error:

Exception in thread "main" java.util.zip.Zipexception: invalid entry Pressed size (expected 5505 but got 7388 bytes).

The idea of the program is to download a compressed file (zip) and save it to the PC disk (do not decompress, just save).

Inside the zipped file I put two txt files and a bmp image, nothing too big, just to test.

I believe that the error is not in the zip file, as I used Winrar to compress it, in this way I think my program is wrong, but I can’t find the error. Follows the code:

public static void main(String[] args) throws MalformedURLException, IOException {

    URL url = new URL("http://localhost/zipado.zip"); //conecta com localhost e busca o arquivo a ser baixado
    InputStream is = url.openStream();  // abre um fluxo de dados para baixar o arquivo
    ZipInputStream zin = new ZipInputStream(is); // cria um fluxo para ler arquivos zipados
    File f = new File("C:/saida/zipado.zip"); // cria um arquivo de saida
    FileOutputStream fout = new FileOutputStream(f); // abre um fluxo para gravar os dados no disco
    ZipOutputStream zos = new ZipOutputStream(fout); // cria um fluxo para zipar dados
    while (true) {
        ZipEntry ze = zin.getNextEntry(); // recebe os "entrys" do arquivos baixado
        if(ze==null) // verifica se ja recebeu todos os "entrys"
            break;
        System.out.println("Unzipping " + ze.getName()); // apresenta os "entrys"
        zos.putNextEntry(ze); // posiciona o próximo entry
        for (int c = zin.read(); c != -1; c = zin.read()) {               
                zos.write(c);   // escreve os dados no arquivo               
        }
        zos.closeEntry(); // fecha o entry
   }
   zos.close(); // fecha para zipar dados
   fout.close(); // fecha para gravar no disco
   zin.close(); // fecha o fluxo de entrada
}

The error occurs when you finish picking up all "entrys", in the following snippet:

zos.closeEntry();

I would like your help to solve this problem.

2 answers

2


Roger, if Voce is already downloading the zipped file Voce does not need to use the Zipentry class, just download the file and save it to disk. Follow an example of file download and save code on disk.

public static void main(String[] args) throws MalformedURLException, IOException {

    File arquivoDeSaida = new File("C://saida//zipado.zip");
    HttpURLConnection url = null;
    InputStream inStream = null;
    FileOutputStream fileOutputStream = null;

    try {

        // conecta ao local host para realizar o download do arquivo
        url = (HttpURLConnection) new URL("http://localhost/zipado.zip").openConnection(); 
        url.setDoInput(true); // configura a conexao para aceitar o recebimento de dados
        url.connect(); // efetiva a conexao ao localhost

        inStream = url.getInputStream();
        fileOutputStream  = new FileOutputStream(arquivoDeSaida); // abre um fluxo para gravar os dados no disco

        byte[] buffer = new byte[4096];
        int bytesLidos = 0;

        while ((bytesLidos = inStream.read(buffer, 0, buffer.length)) > 0) {
            fileOutputStream.write(buffer, 0, bytesLidos);
            fileOutputStream.flush();
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (url != null)
            url.disconnect();
        if (inStream != null)
            inStream.close();
        if (fileOutputStream != null)
            fileOutputStream.close();
    }
}

In this case we are only downloading the file and saving it on disk.

If it was necessary to download the file and then zip, just download and then use the code to zip.

  • Got it. So you don’t need any special treatment to download compressed files?! Was I "zipping" the "zip"? thanks for the clarification.

  • Exactly, as Voce said Voce was "zipping" a zip while downloading and this is not necessary. The ideal is to always download the file completely and then do what you prefer with the file. Hugs :)

-2

the problem is in the object instance ze. try like this:

ZipEntry ze = new ZipEntry(zin.getNextEntry().getName());
  • Unfortunately this solution did not work. Now returns the error of "Nullpointerexception".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.