Created
February 6, 2013 19:43
-
-
Save fridolin-koch/4725174 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sheet12.simpledownloadclient; | |
import java.io.File; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.net.URL; | |
public class DownloadThread extends Thread { | |
// TODO Att ribute | |
private final URL url; | |
private final File file; | |
private DownloadFrameThreaded gui; | |
// TODO Konstruktor. Soll Datei fuer Download anlegen. | |
public DownloadThread(URL url, File file, DownloadFrameThreaded gui) throws IOException { | |
this.file = file; | |
this.file.createNewFile(); | |
this.url = url; | |
this.gui = gui; | |
} | |
@Override | |
public void run() { | |
InputStream in = null; | |
FileOutputStream out = null; | |
try { | |
// Try to determine the size of the file at `url`. | |
final int size = FileTools.sizeOfFileAtURL(url); | |
try { | |
// Open corresponding input- and output-streams. | |
in = url.openStream(); | |
out = new FileOutputStream(file); | |
// Use a 4kb buffer for transferring the bytes. | |
byte[] buffer = new byte[4096]; | |
int totalBytes = 0; | |
long lastProgressBarUpdate = System.currentTimeMillis(); | |
while (!this.isInterrupted()) { | |
// Read bytes from the input stream and store them in | |
// the buffer. | |
int bytesRead = in.read(buffer); | |
if (bytesRead == -1) { | |
break; | |
} | |
// Write the buffer to disk. | |
out.write(buffer, 0, bytesRead); | |
// Keep track of the number of bytes. | |
totalBytes += bytesRead; | |
// Update the progress every once in a while. | |
long currentTime = System.currentTimeMillis(); | |
if (currentTime > lastProgressBarUpdate + 250 && size > 0) { | |
lastProgressBarUpdate = currentTime; | |
gui.setProgress((int)(totalBytes * 100L / size)); | |
} | |
} | |
if (size > 0) { | |
gui.setProgress((int)(totalBytes * 100L / size)); | |
} | |
} finally { | |
// Make sure the streams are closed. | |
if (in != null) { in.close(); } | |
if (out != null) { out.close(); } | |
//close gui | |
gui.done(); | |
} | |
} catch (IOException ex) { | |
gui.error(ex.toString()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment