java - 如何在 Zip writer 中使用进度条?

标签 java zip progress-bar jprogressbar

我制作了一个程序,让用户选择一个文件,然后要求用户制作一个新的 zip 文件。然后程序将所选文件写入 zip 文件。但我不知道如何设置 JProgressBar 来告诉用户进度。但我不知道如何取得进展。请给我获取进度的代码,以便我可以在进度条中显示它。

最佳答案

一种方法是确定文件的大小,将其分成 n block ,然后使用 ZipOutputStream.write(byte[] b, int off, int len) 方法写入每个 block ,在每次写入操作后更新进度条。

编辑示例代码

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() ;
}

关于java - 如何在 Zip writer 中使用进度条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28611104/

相关文章:

java - 更改CharacterRun的字体类型

java - 读取 ZIP 文件会出现 'invalid LOC header' 异常

html - 有什么办法可以通过网页上的字符来改变文本 "halfway"的颜色吗?

java - 安卓错误 : The RealmClass annotation does not support nested classes

Java 帮助 - StringIndexOutOfBoundsException - 字符串索引超出范围 : -1

包含隐藏文件的 Zip

用于下载 Python3 Flask 生成的 ZipFile 的 Javascript 按钮

c# - asp.net 加载栏

jquery - 元素上的分层渐变

java - 使用 Java 从 MacOS X keystore 获取私钥