[英]Progress Bar time calculation + java
我正在將文件從客戶端傳輸到服務器。 我不知道要轉移多少時間。 但是我的用戶界面將保持不變,而不會引起用戶的任何注意。 我需要以這樣的方式保持進度條:上傳文件之前應該是進度。 我怎樣才能做到這一點。
我對.net中的這種情況有點了解。 但是我們如何在Java中做到這一點呢?
對於真正“不確定”的行動, trashgod的答案是正確的。 您為什么認為您的文件傳輸屬於此類? 您是否從未在Internet上下載過帶有相關進度條的文件? 你能想象沒有嗎?
請參閱下面的示例,該示例是如何使用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;
}
如如何使用進度條所示 ,您可以指定不確定的模式,直到您有足夠的數據來衡量進度或下載結束為止。 確切的實現取決於傳輸的方式。 理想情況下,發送方首先提供長度,但是也有可能隨着數據的累積動態地計算速率。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.