bec7097ae33aa369940ef10d3d312c0ae4577818
[debian/jabref.git] / src / java / net / sf / jabref / net / URLDownload.java
1 /*
2  * Created on 1-Dec-2004
3  *
4  */
5 package net.sf.jabref.net;
6
7 import java.awt.Component;
8 import java.io.BufferedInputStream;
9 import java.io.BufferedOutputStream;
10 import java.io.File;
11 import java.io.FileOutputStream;
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.io.OutputStream;
15 import java.net.URL;
16
17 import javax.swing.ProgressMonitorInputStream;
18
19 /**
20  * @author Erik Putrycz erik.putrycz-at-nrc-cnrc.gc.ca
21  */
22
23 public class URLDownload {  
24     
25     private URL source;
26     private File dest;
27     private Component parent;
28
29     public URLDownload(Component _parent, URL _source, File _dest) {
30         source = _source;
31         dest = _dest;
32         parent = _parent;
33     }
34     
35     public void download() throws IOException {
36         InputStream input = new BufferedInputStream(source.openStream());
37         OutputStream output =  new BufferedOutputStream(new FileOutputStream(dest));
38      
39         try
40           {
41             copy(input, output);
42           }
43         catch (IOException e)
44           {
45             e.printStackTrace();
46           }
47         finally
48           {
49             try
50               {
51                 input.close();
52                 output.close();
53               }
54             catch (Exception e)
55               {
56               }
57           }        
58     }
59
60     public void copy(InputStream in, OutputStream out) throws IOException
61       {
62         InputStream _in = new ProgressMonitorInputStream(parent, "Downloading " + source.toString(), in);
63         byte[] buffer = new byte[512];
64         int reps=0;
65         while(true)
66         {
67             int bytesRead = _in.read(buffer);
68             if(bytesRead == -1) break;
69             out.write(buffer, 0, bytesRead);
70         }        
71       }   
72 }