Siddharth Kumar
Siddharth Kumar

Reputation: 27

How to use progress bar with Zip writer?

I have made a program which let's the user to select a file and then ask the user to make a new zip file. The program then writes the selected file in the zip file. But I don't know how to set a JProgressBar to tell the user the progress. But I don't know how to get the progress. Please give me code to get the progress so that I can show it in progress bar.

Upvotes: 2

Views: 1094

Answers (1)

mazaneicha
mazaneicha

Reputation: 9427

One way would be to determine the size of your file, divide it into n blocks, and then use ZipOutputStream.write(byte[] b, int off, int len) method to write each block, updating the progress bar after each write operation.

EDIT Sample code

public static String zipFile(String fileName) throws Exception {
    File file = new File(fileName);
    File zipfile = new File(fileName+".zip");
    FileInputStream fis = new FileInputStream(file);
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipfile)) ;
    int length = (int)file.length() ;
    byte[] data = new byte[length];
    fis.read(data);
    fis.close();
    zos.putNextEntry(new ZipEntry(file.getName()));
    int iterations = 10 ;
    for (int i = 0 ; i < iterations-1 ; i ++) {
        zos.write(data, i*(length/iterations), (length/iterations));
        System.out.format("%d%%\n", (i+1)*10 ) ;
    }
    zos.write(data, (iterations-1)*(length/iterations), length - (iterations-1)*(length/iterations));
    System.out.format("100%%\n") ;
    zos.closeEntry();
    zos.close();
    return zipfile.getName() ;
}

Upvotes: 1

Related Questions