/* GetURL.java * * This program uses the URL class to download the contents * of a URL and copies them to a file or to the console. * * Derived from "Java Examples in a Nutshell", O'Reilly, 1997. * * Bruce M. Bolden * April 22, 1998 * http://www.cs.uidaho.edu/~bruceb/ */ import java.io.*; import java.net.*; public class GetURL { public static void main( String[] args ) { InputStream in = null; OutputStream out = null; try { // Check the arguments if( (args.length != 1) && (args.length != 2) ) { throw new IllegalArgumentException( "Wrong number of arguments" ); } // Set up the streams URL url = new URL( args[0] ); in = url.openStream(); if( args.length == 2 ) out = new FileOutputStream( args[1] ); else out = System.out; // Copy bytes from the URL to the output stream final int BUF_SIZE = 4096; byte[] buffer = new byte[BUF_SIZE]; int bytesRead; while( (bytesRead = in.read(buffer)) != -1 ) out.write( buffer, 0, bytesRead ); } catch ( Exception e ) { System.err.println( e ); System.err.println( "Usage: java GetURL []" ); } finally { try { in.close(); out.close(); } catch ( Exception e ) { /* do nothing */ } } } }