Download one single webpage into your computer page 1

Charles Li
Copyright © 2005-2006
secret
Index of this article| previous: index |next : download several webpages

Example 1

Download one simple file.
import java.net.*;
import java.io.*;

public class CopyURL {
    // copy url to local file name
    public static void copy(String urlname, String filename) throws Exception {
        URL url = new URL(urlname);
        File file = new File(filename);
        BufferedInputStream in = new BufferedInputStream(url.openConnection().getInputStream());
        FileOutputStream out = new FileOutputStream(file);
        int ch = 0;
        while((ch = in.read())!=-1) {
            out.write(ch);
        }
        in.close();
        out.close();
    }
    
    public static void main(String[] args) throws Exception {
        String urlname = "http://www.charlesli.org/index.html";
        String filename = "test.html";
        copy(urlname, filename);
    }
}

Explanation

Attention

There are some drawbacks about the previous example

  1. the program doesn't check the existence of the file. The original file may be corrupted.
  2. If you have to create folders before you run the program.

Example 2

import java.net.*;
import java.io.*;

public class CopyURL2 {
    // copy url to local file name
    public static void copy(String urlname, String filename) throws Exception {
        URL url = new URL(urlname);
        File file = new File(filename);
        BufferedInputStream in = new BufferedInputStream(url.openConnection().getInputStream());
        FileOutputStream out = new FileOutputStream(file);
        int ch = 0;
        while((ch = in.read())!=-1) {
            out.write(ch);
        }
        in.close();
        out.close();
    }
    
    public static void main(String[] args) throws Exception {
        String urlname = "http://www.charlesli.org/index.html";
        String filename = "folder/test.html";
        File file = new File(filename);
        if(file.exists()) {
            // file already exists, what do you want to do?
            // my program prints out an error message and exit
            System.out.println(filename + " exists.");
            return; // quit the main
        }
        file.getParentFile().mkdirs(); // make all the necessary folders
        copy(urlname, filename);
    }
}

Explanation

index | previous: index | next : download several webpages

Charles' Java Articles | charlesli.org |
Copyright © 2005 Charles Li