001package algs11;
002import stdlib.*;
003/* ***********************************************************************
004 *  Compilation:  javac Wget.java
005 *  Execution:    java Wget url
006 *
007 *  Reads in a URL specified on the command line and saves its contents
008 *  in a file with the given name.
009 *
010 *  % java Wget http://www.cs.princeton.edu/IntroProgramming/datafiles/codes.csv
011 *
012 *************************************************************************/
013
014public class XWget {
015
016        public static void main(String[] args) {
017                args = new String[] { "http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html" };
018
019                // read in data from URL
020                String url = args[0];
021                In in = new In(url);
022                if (!in.exists ())
023                        System.exit (1);
024                String data = in.readAll();
025
026                String filename = url.substring(url.lastIndexOf('/') + 1);
027                if (filename.length () <= 0) {
028                        StdOut.println (data);
029                } else {
030                        // write data to a file
031                        Out out = new Out(filename);
032                        out.println(data);
033                        out.close();
034                        StdOut.println ("Output in file \"" + filename + "\"");
035                }
036        }
037}