Amazon Books
bullet Home
bullet Search This Site
bullet Contact Us

Computers & Internet

Java
bullet Java Main Page
bullet C++ vs. Java
bullet Example
bullet Free E-Books
bullet Chat
bullet Glossary Applet
bullet Java News From Yahoo!
bullet Q & A Archive
bullet Message Board

Links
bullet Add Your Link Here
bullet Jinsight Informática
bullet Java - An Object Oriented Language
bullet Java Programmer Certification Exam And Training
bullet java4less
bullet Applese
bullet FAQ About Servlets
bullet ITtoolbox Portal for Java
bullet Java Bookmark
bullet Java FAQ
bullet javaprepare.com

Other
bullet C++
bullet Computer Science
bullet HTML
bullet Internet Product & Services
bullet Java
bullet JavaScript
bullet Linux
bullet Lotus Notes
bullet TechWeb Today
View Technology headlines at MSNBC
Add MSNBC NewsStand to your Web page

Perry Smith

Java Example

I am asked for examples of code many times a week but I don't have time to reply. Instead, I'll ocassionally put something on this page from projects I'm working on.

I've been looking into some things for an upcoming project involving software for webmasters. Some of the code below may be used in the development process. To use it, save the code in a file called GetURL.java. Compile it. From a DOS prompt type java GetURL http://whateverURLyouwant and press enter.

import java.io.*;
import java.net.*;
/**
 * This program shows a way to download the contents  of a URL.
 * I'm not saying that it's the best way, but it is an example.
 **/

 public class GetURL {
	public static void main(String[] args) {

	   InputStream in = null;
	   OutputStream out = null;

	   try  {
		  // Check arguments
		  if((args.length != 1) && (args.length !=2))
			 throw new IllegalArgumentException("Wrong number of arguments");
		  // Set up streams
		  URL url = new URL(args[00]);  // Create URL
		  in = url.openStream();	   // Open stream to it
		  if (args.length == 2)		// Get output stream
			 out = new FileOutputStream(args[1]);
		  else out = System.out;

		  // Copy bytes from URL to output stream
		  byte[] buffer = new byte[4096];
		  int bytes_read;
		  while((bytes_read = in.read(buffer)) != -1)
			 out.write(buffer, 0, bytes_read);
	   }
	   // On exceptions, print error message and usage message
	   catch (Exception e) {
		  System.err.println(e);
		  System.err.println("Usage: getURL  []");
	   }
	   finally {  // Always close the streams, no matter what.
		  try {
			 in.close();
			 out.close();
		  }
		  catch (Exception e) {}

	   }
	}
 }