Downloading file/files in Java. Multithreading, this works? -
first, needs know i'm relatively new java coding. more precise i'm new object oriented programming.
to question.
i trying create download class updates progress bar given show progress. , possibly else decide give in future update.
the issue that, in head, shouldn't work. can want on "main" method , gui still responsive , quick. in experience in past programming, not possible unless thread gui. why this?
since works, ok way?
class main
package atomicelectronics; import java.io.ioexception; import atomicelectronics.physical.atomframe; import atomicelectronics.utility.download; public class initial { static atomframe atomlauncher; public static void main(string[] args) { atomlauncher = new atomframe(); atomlauncher.start(); system.out.println(integer.max_value); download thedownload = new download(); thedownload.fileprogressbar(atomlauncher.progressbar); try { thedownload.exicute("http://download.videolan.org/pub/videolan/vlc/last/win64/vlc-2.1.3-win64.exe", "c:\\users\\trinaryatom\\appdata\\roaming"); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } // todo add download methods // thedownload.updatebartotal(jprogressbar); // thedownload.updatelabelspeed(string); // thedownload.updatelabeltotal(string); // thedownload.addfile(file); // thedownload.addfiles(files); } }
class atomframe
package atomicelectronics.physical; import javax.swing.jframe; import java.awt.flowlayout; import javax.swing.jprogressbar; public class atomframe extends jframe{ public jprogressbar progressbar; private static final long serialversionuid = 4010489530693307355l; public static void main(string[] args){ atomframe testframe = new atomframe(); testframe.start(); } public atomframe(){ initializecomponents(); } public void initializecomponents(){ this.setsize(400, 400); this.setlocationrelativeto(null); this.setdefaultcloseoperation(jframe.exit_on_close); this.settitle("atom launcher"); this.setlayout(new flowlayout(flowlayout.center, 5, 5)); progressbar = new jprogressbar(); this.add(progressbar); //this.pack(); } public void start() { this.setvisible(true); } public void close() { this.dispose(); } }
class download
package atomicelectronics.utility; import java.io.file; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import java.net.httpurlconnection; import java.net.url; import javax.swing.jprogressbar; public class download { private static final int buffer_size = 4096; private jprogressbar fileprogressbar; public download() { } public void fileprogressbar(jprogressbar filebar) { fileprogressbar = filebar; } public void exicute(string fileurl, string savedir) throws ioexception { url url = new url(fileurl); httpurlconnection httpconn = (httpurlconnection) url.openconnection(); int responsecode = httpconn.getresponsecode(); // check http response code first if (responsecode == httpurlconnection.http_ok) { string filename = ""; string disposition = httpconn.getheaderfield("content-disposition"); string contenttype = httpconn.getcontenttype(); double contentlength = httpconn.getcontentlength(); if (disposition != null) { // extracts file name header field int index = disposition.indexof("filename="); if (index > 0) { filename = disposition.substring(index + 9, disposition.length()); } } else { // extracts file name url filename = fileurl.substring(fileurl.lastindexof("/") + 1, fileurl.length()); } system.out.println("content-type = " + contenttype); system.out.println("content-disposition = " + disposition); system.out.println("content-length = " + contentlength); system.out.println("filename = " + filename); // opens input stream http connection inputstream inputstream = httpconn.getinputstream(); string savefilepath = savedir + file.separator + filename; // opens output stream save file fileoutputstream outputstream = new fileoutputstream(savefilepath); double totalread = 0; int bytesread = -1; byte[] buffer = new byte[buffer_size]; while ((bytesread = inputstream.read(buffer)) != -1) { outputstream.write(buffer, 0, bytesread); totalread += bytesread; system.out.println((totalread / contentlength) * 100); fileprogressbar.setvalue((int)((totalread / contentlength) * 100)); } outputstream.close(); inputstream.close(); system.out.println("file downloaded"); } else { system.out.println("no file download. server replied http code: " + responsecode); } httpconn.disconnect(); }
}
suggestions:
- use swingworker background thread work.
- inside swingworker, set progress "bound" property via
setprogress(int progress)
. value should between 1 , 100. - don't have swingworker/file downloader hold jprogressbar or swing components.
- add propertychangelistener swingworker , monitor changes in progress property.
- never make swing fields (or , and fields) public. limit access, , instead change object state via methods.
- read tutorial concurrency in swing necessary details.
for example, code below gross simplification , downloads no files, should give idea:
import java.awt.*; import java.beans.propertychangeevent; import java.beans.propertychangelistener; import java.util.random; import javax.swing.*; public class initial { static atomframe atomlauncher; public static void main(string[] args) { atomlauncher = new atomframe(); atomlauncher.start(); system.out.println(integer.max_value); final download thedownload = new download(); thedownload.addpropertychangelistener(new propertychangelistener() { @override public void propertychange(propertychangeevent pcevt) { if ("progress".equals(pcevt.getpropertyname())) { int progress = thedownload.getprogress(); atomlauncher.setprogress(progress); } } }); thedownload.execute(); } } class atomframe extends jframe { // ********* should private! private jprogressbar progressbar; private static final long serialversionuid = 4010489530693307355l; public static void main(string[] args) { atomframe testframe = new atomframe(); testframe.start(); } public void setprogress(int progress) { progressbar.setvalue(progress); } public atomframe() { initializecomponents(); } public void initializecomponents() { this.setsize(400, 400); this.setlocationrelativeto(null); this.setdefaultcloseoperation(jframe.exit_on_close); this.settitle("atom launcher"); this.setlayout(new flowlayout(flowlayout.center, 5, 5)); progressbar = new jprogressbar(); this.add(progressbar); // this.pack(); } public void start() { this.setvisible(true); } public void close() { this.dispose(); } } class download extends swingworker<void, void> { private static final long sleep_time = 300; private random random = new random(); @override protected void doinbackground() throws exception { int myprogress = 0; while (myprogress < 100) { myprogress += random.nextint(10); setprogress(myprogress); try { thread.sleep(sleep_time); } catch (interruptedexception e) {} } return null; } }
Comments
Post a Comment