| Amazon Books |
|
Java
Links
Other
|
Java ExampleI 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
|