У меня есть код ниже. Я не могу заставить его работать.Соедините JProgressBar с процессом загрузки
Должен отметить, что URL-адрес перенаправляется. Я имею в виду, что url = http://www.thissite.com
и перенаправляет на http://www.othersite.com
. Но я хочу, чтобы он работал с начальным url
.
public void download(String address, String localFileName, JProgressBar progress) {
OutputStream out = null;
URLConnection conn = null;
InputStream in = null;
try {
URL url = new URL(address);
// Open an output stream to the destination file on our local filesystem
out = new BufferedOutputStream(new FileOutputStream("/MusicDownloads/"+localFileName));
conn = url.openConnection();
in = conn.getInputStream();
int length = conn.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
// Get the data
byte[] buffer = new byte[1024];
int numRead = 0;
while ((numRead = in.read(buffer)) != -1) {
current=0;
out.write(buffer, current, numRead);
current += numRead; //we've progressed a little so update current
progress.setValue(current); //tell progress how far we are
}
// Done! Just clean up and get out
} catch (Exception exception) {
exception.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException ioe) {
// Shouldn't happen, maybe add some logging here if you are not
// fooling around ;)
}
}
}
Я не знаю, как исправить вашу проблему с перенаправлением, но как насчет JProgressBar не работает? Обязательно ли вы набираете этот код вне EDT? Вам нужно будет убедиться, что вы вызываете метод setValue (...) 'JProgressBar *** на EDT. –
i am call download («http://www.site.com», «file.txt», jProgressBar1) l, чтобы начать загрузку, и панель прогресса остается застрявшей –