DownLoader.java



package xmlshare;

import java.io.*;
import java.net.*;
import java.util.*;

/** file down loader */
public class DownLoader {
	
  /** port number */
    public static final int PORT=8080;

  /** private dirname */
    private String prefix;

  /** constructor */
    public DownLoader() {
        prefix = "private" + File.separator;
    }
	
  /** receive request from client */
    public void request( OutputStreamWriter out, String resource ) {

       String message = null;
       try {
           String first = "GET " + "/" + resource + " HTTP/1.0\n\n";
           out.write( first, 0, first.length() );
           out.flush();
        }
	catch( Exception e ){
             System.err.println( e.toString() );
        }
    }

  /** skip headers and save filestream */
    public void getResponse( BufferedReader in, Writer out ) {
         try {
             String line = null;
             boolean flag = false;
             while( (line = in.readLine()) != null ){
                 if( flag ) {
                     out.write( line+'\n', 0, line.length()+1 );
                 }
                 else {
                     if( line.equals( "" ) ) {
                         flag = true;
                     }
                 }
             }
             out.flush();
             out.close();
         }
         catch( Exception e ) {
             System.err.println( e.toString() );
         }
    }

  /** a session */
    public void download( String hostName, String resource ){
        try{
            Socket sock = new Socket( hostName, PORT );
                
                OutputStreamWriter out
                   = new OutputStreamWriter(
                        sock.getOutputStream() );
                BufferedReader in
                   = new BufferedReader(
                       new InputStreamReader(
                          sock.getInputStream() ) );

                FileWriter writer
                  = new FileWriter( prefix + resource );

                request( out, resource );
                getResponse( in, writer );

                sock.close();
        }
        catch( Exception e ){
             System.err.println( e.toString() );
        }
    }
	
  /** start here */
    public static void main( String[] argv ){
        try {
            DownLoader test = new DownLoader();
            test.download( argv[0], argv[1] );
        }
        catch( Exception e ){
             System.err.println( e.toString() );
        }
    }
}