我正在从客户端向服务器传输文件。我不知道转移所需的时间。但是我的UI将简单地保持不变,而不会对用户有任何暗示。我需要保持一个进度条,它应该是进展直到文件上传。我怎么能实现这个目标。
我在.net中了解这种情况。但我们怎么能在java中做到这一点?
答案 0 :(得分:4)
trashgod's回答是正确的。为什么您认为您的文件传输适合此类别?你有没有在互联网上下载一个与之相关的进度条?你能想象不那个吗?
请参阅How do I use JProgressBar to display file copy progress?
的答案中提供的以下示例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;
}
答案 1 :(得分:2)
如How to Use Progress Bars所示,您可以指定 indeterminate mode ,直到您有足够的数据来衡量进度或下载结束。确切的实现取决于转移的发生方式。理想情况下,发送方首先提供长度,但也可以在数据累积时动态计算速率。