I am working on a project that transfers files over a network and I want to incorporate a JProgressBar
to show the progress during file transfer but I need help on that.
Asked
Active
Viewed 1.3k times
3

mKorbel
- 109,525
- 20
- 134
- 319
-
You should expand on what exactly you need help with. Is each file broken up into packets, or do you just know when each file is done transferring? Do you have the percentage, and just need help displaying? Do you have the file copy procedure already done? – Andrei Krotkov Jan 15 '09 at 16:39
-
community wiki? Really? – David Koelle Jan 15 '09 at 16:48
4 Answers
3
You probably would find a ProgressMonitorInputStream easiest, but if that doesn't do enough for you, look at its source code to get exactly what you want.
InputStream in = new BufferedInputStream(
new ProgressMonitorInputStream(
parentComponent,
"Reading " + fileName,
new FileInputStream(fileName)
)
);
To use a different transfer method then substitute an appropriate stream for FileInputStream.

Nick Fortescue
- 43,045
- 26
- 106
- 134
1
It sounds like you should be using a SwingWorker
, as described in this Core Java Tech Tip. See also Using a Swing Worker Thread.

Bill the Lizard
- 398,270
- 210
- 566
- 880

Michael Myers
- 188,989
- 46
- 291
- 292
1
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.swing.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;
}
I'm pretty sure this will work.
-
-
FYI out.write(buffer, current, bytesRead) should be out.write(buffer, 0, bytesRead) – Ed Griffin Mar 11 '16 at 18:57
0
Well here is a tutorial for JProgressBar, maybe that will help.

willcodejavaforfood
- 43,223
- 17
- 81
- 111