0

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. but how can we do it in java?

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
Sri Sri
  • 3,107
  • 7
  • 34
  • 37

2 Answers2

4

trashgod's answer is correct for actions that are truly 'indeterminate'. 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? 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?

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;
}
Community
  • 1
  • 1
Amir Afghani
  • 37,814
  • 16
  • 84
  • 124
2

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.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045