/////// Downloader.java /////// import java.io.*; import java.net.*; import java.util.StringTokenizer; public class Downloader { public Downloader(String url) { try { URL urlobj = new URL(url); String file = simpleFilename(urlobj.getFile()); ser = urlobj.openConnection(); if ( file == null ) { file = ser.getContentType(); file = "download." + file.replace('/','-'); } fileobj = new File(file); out = new FileOutputStream(fileobj); fileCreated = true; // System.runFinalizersOnExit(true); // deprecated java1.2 } catch (MalformedURLException e) { JavaSystem.error(e); } catch (IOException e) { JavaSystem.error(e); } } protected Downloader() {} public boolean isReady() { return (ser != null && out != null); } public boolean isDone() { return done; } public String filename() { return fileobj.getName(); } String simpleFilename(String s) { String a = null; StringTokenizer t = new StringTokenizer(s,"/"); while ( t.hasMoreTokens() ) a = t.nextToken(); return a; } public void download(String msg) { try { ser.setDoOutput(true); PrintWriter out = new PrintWriter(ser.getOutputStream()); out.println(msg); out.close(); download(); } catch (IOException e) { JavaSystem.error(e); } } public void download() { if ( ! isReady() ) return; try { InputStream in = ser.getInputStream(); int c; while ( (c = in.read()) > -1 ) out.write(c); in.close(); out.close(); done = true; } catch (IOException e) { JavaSystem.error(e); } } protected File fileobj = null; protected URLConnection ser = null; protected OutputStream out = null; protected boolean fileCreated = false; protected boolean done = false; public void finalize() { if ( ! done && fileCreated ) fileobj.delete(); } public static void main(String[] args) { if ( args.length < 1 ) { JavaSystem.err.println("Usage: " + "java Downloader URL [name= value] ... "); System.exit(1); } Downloader d = new Downloader(args[0]); if ( ! d.isReady() ) { JavaSystem.err.println("Downloader failed"); d.finalize(); return; } if ( args.length == 1 ) d.download(); else { int i = 0; StringBuffer msg = new StringBuffer(); while ( ++i < args.length ) { msg.append(args[i]); msg.append(URLEncoder.encode(args[++i])); } d.download(new String(msg)); } if ( d.isDone() ) JavaSystem.out.println("Downloaded file: " + d.filename()); else JavaSystem.err.println("file: " + d.filename() + " may be incomplete."); } } // example usage // jv Downloader \ // '"http://SymbolicNet.mcs.kent.edu/cgi-bin/icm.demo?factor+y^2-x^2"'\ // 'polynomial=' '"x^4-y^4"'