简体   繁体   English

进度条时间计算+ Java

[英]Progress Bar time calculation + java

I am transferring file from client to server. 我正在将文件从客户端传输到服务器。 I dont know the amount of time it will take to transfer. 我不知道要转移多少时间。 But my UI will simple remain the same without any intimation to user. 但是我的用户界面将保持不变,而不会引起用户的任何注意。 I need to keep a progress bar in such a way it should be progress till file is uploaded. 我需要以这样的方式保持进度条:上传文件之前应该是进度。 How can i acheive this. 我怎样才能做到这一点。

I am abit aware of this scenario in .net. 我对.net中的这种情况有点了解。 but how can we do it in java? 但是我们如何在Java中做到这一点呢?

trashgod's answer is correct for actions that are truly 'indeterminate'. 对于真正“不确定”的行动, trashgod的答案是正确的。 Why do you think that your file transfer fits into this category? 您为什么认为您的文件传输属于此类? Haven't you ever downloaded a file on the internet with some sort of progress bar associated with it? 您是否从未在Internet上下载过带有相关进度条的文件? Can you imagine not having that? 你能想象没有吗?

See the example below that was provided among the answers to How do I use JProgressBar to display file copy progress? 请参阅下面的示例,该示例是如何使用JProgressBar显示文件复制进度的答案中提供的

public OutputStream loadFile(URL remoteFile, JProgressBar progress) throws IOException
{
    URLConnection connection = remoteFile.openConnection(); //connect to remote file
    InputStream inputStream = connection.getInputStream(); //get stream to read file

    int length = connection.getContentLength(); //find out how long the file is, any good webserver should provide this info
    int current = 0;

    progress.setMaximum(length); //we're going to get this many bytes
    progress.setValue(0); //we've gotten 0 bytes so far

    ByteArrayOutputStream out = new ByteArrayOutputStream(); //create our output steam to build the file here

    byte[] buffer = new byte[1024];
    int bytesRead = 0;

    while((bytesRead = inputStream.read(buffer)) != -1) //keep filling the buffer until we get to the end of the file 
    {   
        out.write(buffer, current, bytesRead); //write the buffer to the file offset = current, length = bytesRead
        current += bytesRead; //we've progressed a little so update current
        progress.setValue(current); //tell progress how far we are
    }
    inputStream.close(); //close our stream

    return out;
}

As shown in How to Use Progress Bars , you can specify indeterminate mode until you either have enough data to gauge progress or the download concludes. 如何使用进度条所示 ,您可以指定不确定的模式,直到您有足够的数据来衡量进度或下载结束为止。 The exact implementation depends on how the transfer takes place. 确切的实现取决于传输的方式。 Ideally, the sender provides the length first, but it may also be possible to calculate the rate dynamically as data accumulates. 理想情况下,发送方首先提供长度,但是也有可能随着数据的累积动态地计算速率。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM