如何在 Java 中显示文件复制操作的进度.不使用 Swing 例如在 Web 应用程序中? [英] How does one display progress of a file copy operation in Java. without using Swing e.g. in a Web app?

查看:58
本文介绍了如何在 Java 中显示文件复制操作的进度.不使用 Swing 例如在 Web 应用程序中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要执行文件复制操作并向用户显示进度条的 Web 应用程序.

I have a web application which needs to perform a file copy operation and show user a progress bar.

目前,复制是通过调用 cpio 完成的,在操作完成之前,它无法向 Java 代码提供进度.虽然可以使用 Java 来监视写入的字节数与读取的字节数以估计复制进度,但我认为如果我用 Java 编写实际的复制操作,可能会有更简单的解决方案.我仍然会使用 cpio 进行存档,但实际复制将由 Java 类执行.

Currently, the copy is being done by calling cpio which cannot give progress to the Java code until after the operation has completed. While it would be possible to use Java to monitor the number of bytes written vs. number of bytes read for an estimate of the copy progress, I think there might be a simpler solution if I code the actual copy operation in Java. I would still use cpio for archiving purposes, but the actual copy would be performed by a Java class.

我在搜索中找到的大部分帮助都与progressMonitor有关,它包含一个swing组件,我不确定它是否可以做我想做的事.我只需要一个整数/双倍的进度,我可以将其作为 100 中的 % 提供给我的 Web 应用程序的进度条组件.

Most of the help I found in my searching was related to progressMonitor, which incorporates a swing component, and I'm not sure that it can do what I want. All I need is an integer/double of the progress which I can feed to my web application's progress bar component as a % out of 100.

推荐答案

以下是如何在 java 中复制文件并在命令行上监控进度:

Here is how to copy a file in java and monitor progress on the commandline:

import java.io.*;

public class FileCopyProgress {
    public static void main(String[] args) {
        System.out.println("copying file");
        File filein  = new File("test.big");
        File fileout = new File("test_out.big");
        FileInputStream  fin  = null;
        FileOutputStream fout = null;
        long length  = filein.length();
        long counter = 0;
        int r = 0;
        byte[] b = new byte[1024];
        try {
                fin  = new FileInputStream(filein);
                fout = new FileOutputStream(fileout);
                while( (r = fin.read(b)) != -1) {
                        counter += r;
                        System.out.println( 1.0 * counter / length );
                        fout.write(b, 0, r);
                }
        }
        catch(Exception e){
                System.out.println("foo");
        }
    }
}

你必须以某种方式更新你的进度条而不是 System.out.println().我希望这会有所帮助,但也许我没有理解您的问题.

You would have to somehow update your progress bar instead of the System.out.println(). I hope this helps, but maybe i did not understand your question.

这篇关于如何在 Java 中显示文件复制操作的进度.不使用 Swing 例如在 Web 应用程序中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆