Wednesday, October 15, 2008

How to write a file downloader in java

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class Downloader
    implements java.lang.Runnable
{

    public Downloader(java.net.URL url, java.io.File destination)
    {
        length = -1;
        progress = 0;
        thread = new Thread(this);
        stop = true;
        this.url = url;
        file = destination;
    }

    public void run()
    {
        java.io.InputStream in = null;
        java.io.OutputStream out = null;
        try
        {
            java.net.URLConnection connection = url.openConnection();
            in = connection.getInputStream();
            out = new FileOutputStream(file);
            byte data[] = new byte[4096];
            length = connection.getContentLength();
            int total;
            while (!stop && (total = in.read(data)) > 0) 
            {
                out.write(data, 0, total);
                progress += total;
            }
        }
        catch (java.lang.Exception e)
        {
            e.printStackTrace();
            stop = true;
        }
        try
        {
            in.close();
            out.close();
        }
        catch (java.lang.Exception e)
        {
            e.printStackTrace();
        }
        if (stop)
            try
            {
                if (file.exists())
                    file.delete();
            }
            catch (java.lang.Exception e)
            {
                e.printStackTrace();
            }
    }

    public void start()
    {
        stop = false;
        thread.start();
    }

    public void join()
    {
        try
        {
            thread.join();
        }
        catch (java.lang.InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    public void cancel()
    {
        stop = true;
    }

    public int getLength()
    {
        return length;
    }

    public int getProgress()
    {
        return progress;
    }

    public int getProgressInPercent()
    {
        return (int)(((double)progress / (double)length) * 100D);
    }

    public boolean completed()
    {
        return !thread.isAlive() && progress == length;
    }

    public boolean stopped()
    {
        return !thread.isAlive() && stop;
    }

    private java.net.URL url;
    private java.io.File file;
    private int length;
    private int progress;
    private java.lang.Thread thread;
    private boolean stop;
}

No comments:

Post a Comment