Today I tried looking on the web but using search strings such as "Java", "Download", "Web" just doesn't cut it. :D
So I figured that something had to sit in the java.net package.
Instead of having a WebClient like C#, you use the URL class.
One would ask why do you download from the URL class? Well like Java is, you don't make use of the URL class itself but it is just another "factory" to obtain the connection to that desired url. From the connection you obtain the input stream and thats how you download.
Here is a sample code I've written which downloads a file and reports the progress to you every second:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
interface DowloadEvent
{
int getUpdateInterval();
void update(int received, int total);
}
class Report implements DowloadEvent
{
public int getUpdateInterval()
{
return 1000;
}
public void update(int received, int total)
{
System.out.println((int)(received / (float)total * 100) + " % completed");
}
}
class DownloadHandler
{
public static URLConnection getConnection(String url) throws MalformedURLException, IOException
{
return new URL(url).openConnection();
}
public static void downloadData(URLConnection from, OutputStream output, DowloadEvent downloadEvent) throws IOException
{
InputStream input = from.getInputStream();
byte[] data = new byte[1024];
long time;
int received = 0;
int rec;
int total = from.getContentLength();
time = System.currentTimeMillis();
while((rec = input.read(data)) > -1)
{
output.write(data, 0, rec);
received += rec;
if(System.currentTimeMillis() - time >= downloadEvent.getUpdateInterval())
{
time = System.currentTimeMillis();
downloadEvent.update(received, total);
}
}
input.close();
}
}
public class Main
{
public static void main(String[] args)
{
try
{
String urlStr = "http://heanet.dl.sourceforge.net/sourceforge/sevenzip/7z455.msi";
PrintStream p = System.out;
long length;
p.println("Connecting to: " + urlStr);
URLConnection con = DownloadHandler.getConnection(urlStr);
con.setUseCaches(false);
length = con.getContentLength();
FileOutputStream output = new FileOutputStream("7z455.msi");
p.println("File size: " + (int)(length / 1024.0f) + " Kbytes");
p.println("Downloading...");
DownloadHandler.downloadData(con, output, new Report());
p.println("Done.");
output.close();
}
catch (MalformedURLException ex)
{
ex.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
Hope you like it, or find it useful. Enjoy and may the Lord Jesus Bless you!
No comments:
Post a Comment