Java Development
Articles
Downloading the Contents of a URL
Published: August 11, 2007
Print    Email

This tutorial is designed to provide a basic overview of how to download the contents of a URL by using the URL class .When you have completed the tutorial you will have written a simple application that downloads a page . It is assumed that you have an understanding of how to program in Java and are familiar with the development environment you are using.

The first thing you need to is  familiar with Class URL

Class URL represents a Uniform Resource Locator, a pointer to a "resource" on the World Wide Web. A resource can be something as simple as a file or a directory, or it can be a reference to a more complicated object, such as a query to a database or to a search engine

Method openStream opens a connection to this URL and returns an InputStream for reading from that connection.

Below is the source code. 

import java.io.*;
import java.net.*;
public class DownloandURL {
    public static void main(String[  ] args) {
        InputStream input= null;  
        OutputStream output= null;
        try {
            if ((args.length != 1)&& (args.length != 2))
                throw new IllegalArgumentException("Wrong number of args");    
            // Set up the streams
            URL url = new URL(args[0]);   // Create the URL
            input= url.openStream( );        // Open a stream to it
            if (args.length == 2)         // Get an appropriate output stream
                output = new FileOutputStream(args[1]);
            else output = System.out;
            // Now copy bytes from the URL to the output stream
            byte[  ] buffer = new byte[4096];
            int bytes_read;
            while((bytes_read = in.read(buffer)) != -1)
                out.write(buffer, 0, bytes_read);
        }
        catch (Exception e) {
            System.err.println(e);
        }
        finally {  // Always close the streams, no matter what.
            try {
            in.close( ); 
            out.close( ); }
        catch (Exception e) {  }
        }
    }
}



View Comments (0)
Latest Articles
Java Threads

Delete file using File.delete( ) method

Copying Files in Java

Downloading the Contents of a URL

Java FTP Source Code

Processing XML with Java

Generating Random Numbers

Java Lexical Structure

Serializing

Learning java
Latest Posts
Last news from Bahrain islands
Posted by ribrothetit

Please, help me
Posted by FthrOfIIIChlds

Beginners tutorial!
Posted by perz

Health and Beauty FOREVER
Posted by SKACTANDATE

buy xanax fergana
Posted by FleseeKip

Newsletter
Subscribe to our Newsletter!

Your Email: